({
getCurrentValue,
subscribe,
}: {
getCurrentValue: () => Value,
subscribe: (callback: Function) => () => void,
})
| 283 | |
| 284 | // Copied from https://github.com/facebook/react/pull/15022 |
| 285 | export function useSubscription<Value>({ |
| 286 | getCurrentValue, |
| 287 | subscribe, |
| 288 | }: { |
| 289 | getCurrentValue: () => Value, |
| 290 | subscribe: (callback: Function) => () => void, |
| 291 | }): Value { |
| 292 | const [state, setState] = useState(() => ({ |
| 293 | getCurrentValue, |
| 294 | subscribe, |
| 295 | value: getCurrentValue(), |
| 296 | })); |
| 297 | |
| 298 | if ( |
| 299 | state.getCurrentValue !== getCurrentValue || |
| 300 | state.subscribe !== subscribe |
| 301 | ) { |
| 302 | setState({ |
| 303 | getCurrentValue, |
| 304 | subscribe, |
| 305 | value: getCurrentValue(), |
| 306 | }); |
| 307 | } |
| 308 | |
| 309 | useEffect(() => { |
| 310 | let didUnsubscribe = false; |
| 311 | |
| 312 | const checkForUpdates = () => { |
| 313 | if (didUnsubscribe) { |
| 314 | return; |
| 315 | } |
| 316 | |
| 317 | setState(prevState => { |
| 318 | if ( |
| 319 | prevState.getCurrentValue !== getCurrentValue || |
| 320 | prevState.subscribe !== subscribe |
| 321 | ) { |
| 322 | return prevState; |
| 323 | } |
| 324 | |
| 325 | const value = getCurrentValue(); |
| 326 | if (prevState.value === value) { |
| 327 | return prevState; |
| 328 | } |
| 329 | |
| 330 | return {...prevState, value}; |
| 331 | }); |
| 332 | }; |
| 333 | const unsubscribe = subscribe(checkForUpdates); |
| 334 | |
| 335 | checkForUpdates(); |
| 336 | |
| 337 | return () => { |
| 338 | didUnsubscribe = true; |
| 339 | unsubscribe(); |
| 340 | }; |
| 341 | }, [getCurrentValue, subscribe]); |
| 342 |
no test coverage detected