How to share data across multiple components with react-query useMutation

Viewed 2040

I'm looking for a solution to share data across a React-Query mutation without having to create my own internal state or context.

I created a custom hook that takes care of the API call.

myData.ts

const useDataMutation = () => useMutation('MY_DATA_MUTATION', postData);

Then, I use my custom hook in different components.

Component1 is in charge of mutating. The response data will be available in data once the mutate is successful.

Component1.tsx

  const { mutate, data } = useDataMutation();
  
  useEffect(() => mutate('some_data'), []); 

In another nested component, I want to access the data which came back from the response. But I don't want to pass down the data to 3-4 layers of components. And I wanted to avoid using a Context to access this data.

What I want is something like this:

Component2.tsx

  const { data } = useDataMutation();
  
  console.log({ data }); // log data once available. 

But in this example, the data from Component2.ts is always undefined.

Is there a simple way to achieve something like this?

Thank you.

2 Answers

at the moment, mutations don't share data across instances like queries do. There is an open issue about it, and contributions are welcome.

If you're using @apollo/client then you can read the previously fetched data directly from the cache.

import Query from './query.ts'

const { todo } = client.readQuery({
  query: Query,
  variables: {}
})

That will not fetch the data from your server again and instead fetch it from the apollo cache. So you can fetch it using the hook or in the parent component and then 5 levels down you can just pull it again from the cache using the same hook.

When you're using a mutation it will update data in the cache if the properties in the query is the same as before, so if you have a query for getUser and a mutation for updateUser I think the mutation should automatically update the getuser cache data if the data aligns with the mutation data. I'm not sure about this.

Related