Search code examples
reactjsreduxgraphqlapollo

How to convert Redux app to GraphQL/Apollo?


I'm refactoring an express+react app that is using redux and I would like to switch to graphql (apollo), but I have a few things that are not quite clear.

So the general flow is there's GET request to fetch the data (an array of objects) that are then stored in redux store and using selectors paginated and presented as a list. The user then can edit the entries (entries are modified in redux store) and he can then "publish" that takes data from redux store and calls POST endpoint.

How would I model that in graphql? Do I paginate using a graphql query (using offset/limit in DB)? How would I then be able to modify the entries in memory and publish all of the entries at once once I'm done editing?


Solution

  • In Apollo it is quite simple:

    • fetched data is stored in normalizing cache (list and items separately);
    • component can use useQuery hook to fetch data (using caching client);
    • render items with edit capabilities;
    • on your onChange/onSave events call mutation function (returned from useMutation hook) passing one or more records data (you want to update) as variables;
    • data sent to API results in response (mutation resolver) you can use (in onCompleted handler) to update local cache (writeQuery) or call refetch query (by calling fn/handler from useQuery), both will force rerendering component with updated data;

    Yes, pagination can be done using query variables, fetch more etc.