Hi there,
I am trying to use apollo as a state management library. I would like to fetch some data from my graphql server and use the data directly in a component. After that I would like to change some kind of property values in this data from client. Maybe I can fetch more detail from server for this particular data. Imagine you have a product list. And you have two view mode: Compact and detailed. In compact mode you can change a particular product view without changing whole list view mode. So how should I manage this state? I have a solution but I don’t sure that is the perfect way.
I am using apollo client query directly in my component (by using withApollo or useApolloClient hook). I fetch the product list from server by using “network-only” fetch policy. By the way all product item has a unique id.
useEffect(() => {
client.query({
query: GET_PRODUCTS,
variables: { viewMode },
fetchPolicy: 'network-only',
});
}, [viewMode]);
So Apollo writes products to cache and than I can reach this data by using useQuery hook with “cache-only” fetch policy.
const { data: { products } = useQuery(GET_PRODUCTS, {
variables,
nextFetchPolicy: 'cache-only',
});
With this way I am able to be change any product data by using cache.writeFragment with product id.
cache.writeFragment({
id: cache.identify(obj),
fragment,
data,
});
P.S: writeFragment updates product item and product immediately change in UI.
Is this solution accaptable? This is working perfectly but I would like to be sure is this a right way.
Thanks