Skip to content

Instantly share code, notes, and snippets.

@yue4u
Created December 13, 2019 07:49
Show Gist options
  • Save yue4u/840f1e62ecb8c7e8873ea79ab4f0efe3 to your computer and use it in GitHub Desktop.
Save yue4u/840f1e62ecb8c7e8873ea79ab4f0efe3 to your computer and use it in GitHub Desktop.
import { BehaviorSubject, Subject, combineLatest } from 'rxjs'
import { useState, useEffect } from 'react'
import { skip, filter } from 'rxjs/operators'
export const useSharedState = <T>(
defaultState: T,
subject: Subject<T>
): [T, typeof useState] => {
const [value, setState] = useState(defaultState)
useEffect(() => {
const sub = subject.subscribe(s => setState(s))
return () => sub.unsubscribe()
})
const newSetState = (state: T) => subject.next(state)
// @ts-ignore
return [value, newSetState]
}
export const setPartial = <T>(
subject: BehaviorSubject<T>,
partial: Partial<T>
) => {
const prev = subject.getValue()
subject.next({ ...prev, ...partial })
}
@apappas1129
Copy link

apappas1129 commented Oct 3, 2020

I recently found out about this implementation. And landed on this one. May I ask on how should the code look like when doing API calls (say, with axios-observable) and setting them on the global state (useSharedState) ? Also, I don't seem to understand what the setPartial is for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment