Apollo Client and React Redux-Toolkit how should state management be?
Asked Answered
G

1

6

I am extremely confused. Before the real problem comes, let me tell you how I got started. maybe i'm on the wrong way. so you can suggest other ways

We do not use graphql for sign-in and sign-up in our project. Sign up consists of 5 stages and I used react redux-toolkit because I had trouble managing my state. I used the axios library for my sign-in and sign-up api calls.

I split modules into slice with redux. it sounded very simple at first. I was setting the data returned from axios to the state of the relevant slice.

For example, after the sign-up first step, I was setting the result I got from axios to the firstStepData key in the SignUpSlice state. then I can access firstStepData from other steps.

So far, no problem.

All our API requests after the user login are configured with graphql. the problem starts here. actually not a problem. i just don't know how to do.

axios supports graphql, but usage is not exactly what I want. so I thought apollo-client would be more suitable for my project.

let's consider a settings page for example.

my settings page code;

const GET_SETTINGS = gql`
  ...query
`;

const SettingsPage = () => {
  const { loading, error, data } = useQuery(GET_SETTINGS);

  if (loading) return 'Loading...';
  if (error) return `Error!`;

   return (
      <Settings>
         <Logo />
         <UpdateForm />
         <DeleteButton />
      </Settings>
   );
};

So, i can transfer the data to subcomponents like this <Settings data={data}> But isn't it tiring to transfer data like this in nested components? Or if I want to access this data from other components that do not belong settings page? How can I transfer this data to subcomponents?

In this case, should I follow the way followed in sign-up? Do I have to create SettingsSlice with redux, then set the data from GET_SETTINGS to the SettingsSlice state and access from other components?

my brain is on fire.

Gerrygerrymander answered 24/4, 2021 at 19:22 Comment(0)
B
8

Apollo is a shared cache. You can just do useQuery(GET_SETTINGS); in every component that needs that data - if it's already in the cache, nothing to be done. Otherwise it will get it.

No need to replicate that in redux - apollo is now your cache state manager while redux is there for all the other data.

Beriosova answered 24/4, 2021 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.