Home > Blockchain >  React Query- How to recall api from other component
React Query- How to recall api from other component

Time:12-21

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

CodePudding user response:

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'] });
  };

  ...
}

CodePudding user response:

To update data in component 'A' when the data in component 'B' is updated, you can use the React Context API to pass data from component 'B' to component 'A'.

Here's a simplified example of how you can do this:

1- Create a context in component 'A':

 const MyDataContext = React.createContext();

 function ComponentA() {
   // Initialize state for the data that you want to 
   //pass to component B
  const [data, setData] = useState(null);

 // Fetch data from the API and update the state
  useEffect(() => {
     async function fetchData() {
     const result = await fetch('/api/data');
     setData(await result.json());
    }
    fetchData();
   }, []);

 return (
  // Provide the data through the context so it can be 
   //accessed by component B
     <MyDataContext.Provider value={{ data, setData }}>
      {/* Render component B here */}
      <ComponentB />
    </MyDataContext.Provider>
  );
 }
 

2- In component 'B', access the data from the context and update it when necessary:

 function ComponentB() {
  // Use the context to access the data and the setData 
  //function
  const { data, setData } = useContext(MyDataContext);

   // When you want to update the data in component A, 
   //call setData with the new value
    const handleUpdate = () => {
      setData(newValue);
   }

    return (
     <div>
        {/* Render the data here */}
       {data}
     <button onClick={handleUpdate}>Update 
       data</button>
    </div>
  );
 }

This way, when you click the "Update data" button in component 'B', the data in component 'B' will be updated with the new value.

I hope this helps! Let me know if you have any questions.

  • Related