Using onSuccess with select in custom hooks #3229
-
I'm facing a question of best practice with running side effects from the Here's an example of the setup I'm describing: function useCharacters<SelectedData = Data>(
options?: Omit<
UseQueryOptions<
Data,
unknown,
SelectedData,
ReturnType<typeof queryKeys.characters>
>,
'queryKey' | 'queryFn'
>
) {
return useQuery(
queryKeys.characters,
async () => {
// api request
},
{
...options,
onSuccess: callAll(config?.onSuccess, (data) => {
runSideEffect(data)
})
}
);
}
function useCharacter(characterId: number) {
return useCharacters({
select: (data) => data.find((character) => character.id === characterId),
});
} By design, A quick and dirty solution (or maybe it's the recommended way?) would be to manually select out the full data in the main // ...
onSuccess: callAll(config?.onSuccess, () => {
const queryData = queryClient.getQueryData(queryKeys.characters);
runSideEffect(queryData)
}) An alternative solution might be to set up a custom hook that "listens" for that query's data changing and runs the side effect when it does. My question is: are either of the two proposed solutions good practice, or am I thinking about this problem in the wrong way? Or does it make any sense to update React Query such that the "unmodified" data gets passed to Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Now if you have two observers with different select outputs, I'm having a hard time coming up with a side-effect that should be run twice after a fetch, but with the same original / full data 🤔 If your intention is to only run the side-effect once per fetch, have a look at the global queryCache callbacks. |
Beta Was this translation helpful? Give feedback.
onSuccess
will run one time for each useQuery instance (=observer), and for each one, it will get the observer specific data, which is the one it gets fromselect
.Now if you have two observers with different select outputs, I'm having a hard time coming up with a side-effect that should be run twice after a fetch, but with the same original / full data 🤔
If your intention is to only run the side-effect once per fetch, have a look at the global queryCache callbacks.