I’m working on moving some parts of my app’s Contexts into RecoilJS atoms and wondering about the best way to handle loading reactive data. Has anyone found a nice pattern for this?
Here is a contrived example showing a useEffect
pattern, allowing the isLoading
state of the subscription to be used. I’ve used this pattern in a couple of components so far, but haven’t done extensive testing as I’m only experimenting with Recoil and curious if anyone else has used it with success.
type SiteType = {
_id: string
name: string
projectId: string
}
export const sitesState = atom({
key: 'SitesState',
default: [] as SiteType[]
})
export const useSites = (projectId) => {
const [recoilSites, setSitesState] = useRecoilState(sitesState)
const { isLoading, sites } = useTracker(() => {
const data = { isLoading: true, sites: [] }
const siteHandler = Meteor.subscribe('sitePublisher')
if (siteHandler.ready()) {
data.isLoading = false
data.sites = SiteCollection.find({ projectId }).fetch()
}
return data
})
useEffect(() => {
// pseudo code here!
// deep compare recoilSites with sites returned from tracker
// if different, setSitesState
setSitesState(sites)
}, [sites])
return isLoading;
}