Home > Mobile >  Using RTK query how do I add data to my state without a call to the server?
Using RTK query how do I add data to my state without a call to the server?

Time:12-05

I'm building my first app using RTK query. I need to set my authorization token in my headers. It is stored in a cookie, but they can't be accessed from the apiSlice, which means I need to store the token in my states which I'd have access to when setting my headers.

I get the token from my cookies when the app first starts, but I'm failing to understand how do I store it in my state, now that I use RTK query? I'm not making any API call, I already have the data. How do I store it in my slice?

CodePudding user response:

The point of RTK Query is to make calls to the server and store the result of that call to the server.

RTK Query does not replace all your other state management - it just takes over that one aspect. If you have non-server-data, you should still be using a normal slice for that, not try to put that into RTK Query.

Apart from that: if you have a token that is in a cookie, there is probably no need to read that into your store and attach it to future requests. The point of cookies is that they are sent back and forth between the browser and the server - you don't have to manually do anything here, besides setting the credentials: "include" option.

CodePudding user response:

To add data to your state without making a call to the server using RTK query, you can use the update() method of your slice. This method allows you to update your state with new data without dispatching an action.

For example, if you have a slice called "auth" with a property called "token" that you want to update with your authorization token, you can use the following code:

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    token: null
  },
  reducers: {
    // Add your reducer functions here
  }
});

// Get your authorization token from the cookie
const token = getTokenFromCookie();

// Update the state with the new token
authSlice.update(state => {
  state.token = token;
  return state;
});

This will update your state with the new token without making a call to the server. You can then access the token in your state using the select() method of your slice.

const token = authSlice.select(state => state.token);

You can then use the token to set the headers of your API requests.

const headers = {
  Authorization: `Bearer ${token}`
};

By using the update() method of your slice, you can easily add data to your state without making a call to the server.

  • Related