I'm pretty new to React and trying to add an JWT token to my headers for authorized api calls.
// client.ts
export const client = axios.create({
baseURL: URLS.local,
responseType: 'json',
timeout: 180000,
});
const state = store.getState(); // Error caused by this
export const authClient = axios.create({
baseURL: URLS.local,
responseType: 'json',
timeout: 180000,
headers: { 'Authorization': state.account.token, 'Content-Type': 'application/json' }
});
// accountSlice.ts
export const login = createAsyncThunk(
'account/account',
async () => {
const response = await authClient.get('/api/account/account');
return response.data;
}
);
export const login2 = createAsyncThunk(
'account/account',
async (_, { getState }) => {
console.log('login called');
const { token } = getState().account; // Error caused by this
const response = await client.get('/api/account/account', {headers: { 'Authorization': token, 'Content-Type': 'application/json' }} );
return response.data;
}
);
const accountSlice = createSlice({
name: 'account',
initialState,
// non async calls
reducers: {
reset: () => {
return initialState;
},
},
// async calls
extraReducers: builder => {
builder.addCase(authenticate.fulfilled, (state, action) => {
state.status = 'pending';
state.token = action.payload.idToken;
})
builder.addCase(login.fulfilled, (state, action) => {
state.status = 'fulfilled';
state.isAuthenticated = true;
state.profile = action.payload;
})
builder.addCase(logout.fulfilled, (state) => {
state = initialState;
})
}
})
So I have an post call that gets the JWT token and then I set it to state.token. But now I need to use it to add to all the other headers on my api calls. I trying 2 different methods and both are failing me.
1st method was trying to access the token in client.ts and creating a axios client with the header, but because I have 'const state = store.getState()', I'm getting error where one of my reducer provider is not being found in the store.ts.
2ns method was trying to add the token on the createAsyncThunk when api calls are made, but the problem here is that the parameter {getState} is not working as expected (https://redux-toolkit.js.org/api/createAsyncThunk). I currently get this error "Property 'account' does not exist on type 'unknown'."
I would prefer the 1st method since it will be cleaner if anyone knows what's wrong with my code.
Thanks