Đỗ Duy Đoàn
Đỗ Duy Đoàn

Reputation: 21

React Query- How to recall api from other component

I have component A,I call react query inside,I have component B, it make update data of api. How when i update data from api B will it call back api to update new data. Thanks

I don't know how to do it, please help

Upvotes: 0

Views: 1127

Answers (1)

Chris
Chris

Reputation: 6631

If you're using mutations from react-query, you can call queryClient.invalidateQueries() from within the onSuccess handler as described in the documentation.

That looks like this:

const mutationFn = () => fetch(...);

const ComponentB = () => {
  const queryClient = useQueryClient()

  const mutation = useMutation({
    mutationFn,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['query-key'] })
    },
  });

  ...
}

If you're not using mutations, it is basically the same but without the onSuccess handler.

const doRequest = () => fetch(...);

const ComponentB = () => {
  const queryClient = useQueryClient()

  const performUpdate = async () => {
    await doRequest();
    queryClient.invalidateQueries({ queryKey: ['query-key'] });
  };

  ...
}

Upvotes: 2

Related Questions