TanStackT
TanStack13mo ago
3 replies
faint-white

using `select` as an `onSuccess` replacement

in reference to this article

https://tkdodo.eu/blog/breaking-react-querys-api-on-purpose#react-query-v5 (great article btw)

the recommend way to sync state is to use useEffect in use land

export function useTodos(filters) {
  const { dispatch } = useDispatch()

  const query = useQuery({
    queryKey: ['todos', 'list', { filters }],
    queryFn: () => fetchTodos(filters),
    staleTime: 2 * 60 * 1000,
  })

  React.useEffect(() => {
    if (query.data) {
      dispatch(setTodos(query.data))
    }
  }, [query.data])

  return query
}


now according the docs, select reruns when the
data
changes assuming data means cached data this means, I ca write something like this


export function useTodos(filters) {
  const { dispatch } = useDispatch()

  const query = useQuery({
    queryKey: ['todos', 'list', { filters }],
    queryFn: () => fetchTodos(filters),
    staleTime: 2 * 60 * 1000,
    select: (data) => {
      if (data) {
        dispatch(setTodos(data))
      }
      return data
    }
  })
  return query
}


is there any drawbacks to this approach?
Was this page helpful?