Get Data From Store For RTK Queries
Oluwaseyi Komolafe
Posted on January 22, 2023
Redux at the beginning was a lot to phantom, at least for me. I hated Redux to be honest. All the folder structuring and whatnot.
I always hoped not to have to use it, until, the emergence of the redux toolkit, coupled with the RTK Query for making endpoint call.
Things have become more easier and productivity has increased.
Working with the RTK Query to make CRUD request is one of the best things to ever happen since invention of pizza😅.
Well one thing that turns out to be a blocker for most people I've met is accessing the redux state while making queries or mutation.
It can be tricky though as the documentation doesn't really do justice to it. So quickly I'll show you how to access let's say a stored access token from the redux state when accessing a protected API route.
1. Creating A Token Slice
import {createSlice} from '@reduxjs/toolkit';
const initialState = {
auth: <any>{},
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
setAuth: (state, action) => {
return {...state, auth: action.payload};
},
clearAuth: () => {
return {auth: {}};
},
},
});
const {reducer, actions} = authSlice;
export const {
setAuth,
clearAuth,} = actions;
export default reducer;
Here now we've created a slice that we can dispatch to store the response of a log in action by the user.
We can then proceed to -
2. access it in our createApi query.
baseQuery: fetchBaseQuery({
baseUrl,
prepareHeaders: (headers, {getState}) => {
const token = (getState() as RootState)?.auth?.auth?.token;
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
return headers;
},
Above we are using the prepareHeader parameter to access the redux state i.e. getState and we follow the chain till we hit our access token.
Adding this in the prepareHeader prop of rtk's createApi gives all our queries and mutations access to the token.
This method works, other than the regular use selector because our query or mutation logic is not going to be a component and this limits the use of React Hooks.
Let me know if this helps you.
Posted on January 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.