CalvinTorra
How do I get the data from useQuery in onSuccess callback?
react-query

There was a bit of confusion on how to get data back from useQuery hook. The developer asking this question thought that the onSuccess key was how you finally got your data from useQuery.

The onSuccess and onError are callback functions that are called after a fetch has succeeded or failed.

They’re optional and useful. They’re called and passed the data that has been retrieved from the useQuery call so that you can trigger side effects, such as modal popups or something similar with your new data.

const { data } = useQuery("posts", fetchPosts, {
  onSuccess: (data) => console.table(data.data),
  onError: (error) => console.log(error.message)
});
/*
  Updating the name from data to dataRetrieved, makes it more clear.
  We're usually expecting the { data }
  
*/
const { data } = useQuery("posts", fetchPosts, {
  onSuccess: (dataRetrieved) => console.table(dataRetrieved.data),
  onError: (error) => console.log(error.message)
});

The data that you are expecting is { data }, this is the variable that you are probably looking to return after a successful fetch in most cases, not dataRetrieved.

After Post Requests

Similarly, after a post request, we want to invalidate the key, The invalidation of the key tells React Query to re-fetch and update the data.

So after a post request to our API (updating the database), we’d normally want that new data to be shown. If the key is not invalidated, we’ll see old data rather than new data.

To do this we need to pass onSuccess the queryClient as well as set invalidateQueries with the key we want to update.

// Post data to our API
const poster = (id) => {
  return axios.post(`https://yourapi.com/posts`, id);
};
// Tell React Query to invalidate the posts key
// and fetch the new data again to see our changes.
export const useAddPosts = () => {
  const queryClient = useQueryClient();
  return useMutation(poster, {
    onSuccess: () => {
      queryClient.invalidateQueries("posts");
    }
  });
};
Contact Me