jotaijs / jotai-tanstack-query

Jotai integration library for TanStack Query
MIT License
210 stars 14 forks source link

Passing props to jotai-tanstack-query #49

Closed dmaskasky closed 1 year ago

dmaskasky commented 1 year ago

How can I pass props to atomWithQuery?

I realize atomWithQuery is global / context scoped whereas props are component scoped. But queryCache is context scoped and react-query accepts unmemoized props.

I want to bring my fetched data into the jotai context store so I can write derived atoms reactive to this data.

If I could somehow pass props to a context-scoped jotai atom, then I would be able to use jotai-tanstack-query instead of react-query, which would also resolve the related issue below for me.

Related: https://github.com/jotaijs/jotai-tanstack-query/issues/48

dmaskasky commented 1 year ago

The recommended approach for passing props is to create and memoize jotai atoms in a component. How would context/global scoped atoms get a reference to the atom config to access the fetched data?

dai-shi commented 1 year ago

How would context/global scoped atoms get a reference to the atom config to access the fetched data?

Can you elaborate a bit? Can you explain it without atomWithQuery?

dmaskasky commented 1 year ago

How would context/global scoped atoms get a reference to the atom config to access the fetched data?

const derivedPostAtom = atom(get => {
  get(postQueryAtom)  // <--- How do I get this?
})

function Post(id: number) {
  const postQueryAtom = useMemo(() => {
    const postQueryAtom = atomWithQuery(() => ({
      queryKey: ['posts', id],
      queryFn: async ([_, id]) => {
        const { data } = await getPost(id)
        return data
      }
    }))
    return postQueryAtom
  }, [id])

  const { status, data, error, isFetching } = useAtomValue(postQueryAtom)
  ...
}
dai-shi commented 1 year ago

https://github.com/jotaijs/jotai-tanstack-query/issues/49#issuecomment-1750108716

get(postQueryAtom) // <--- How do I get this?

As it's not global, you need to use context or put the atom config in a global atom (but it can only holds one.)

Or, use bunshi.

dmaskasky commented 1 year ago

I see. The prop is component scoped as it the resulting data so the atom would necessarily also be component scoped.