skip to Main Content

Hello guys i have mern stack project using redux toolkit and want to access my accessToken from server in client side. I have apiCalls folder inside the folder i have a axios.create and want to access the accessToken after loggedIn and save the token in redux state, but when i trying to call the useSelector to select the accessToken it says error React Hook "useSelector" cannot be called at the top level. Is there another way to access the jwt accessToken ?? im new to this. Thanks

apiCalls :

import React from 'react';
import axios from 'axios';
import { useSelector } from 'react-redux';

const BASE_URL = "http://localhost:5000";

const user = useSelector((state) => state.user.accessToken);
const TOKEN = user; 

export const publicRequest = axios.create({
    baseURL: BASE_URL
})

export const userMethod = axios.create({
    baseURL: BASE_URL,
    headers: {token: `Bearer ${TOKEN}`}
})

userRedux :

import { createSlice } from '@reduxjs/toolkit'


const userSlice = createSlice({
    name: "user",
    initialState: {
       currentUser: null,
       isFetching: false,
       error: false
    },
    reducers: {
        loginStart: (state) => {
            state.isFetching = true;
        },
        loginSuccess: (state, action) => {
            state.isFetching = false;
            state.currentUser = action.payload;
        },
        loginFailure: (state) => {
            state.isFetching = false;
            state.error = true;
        },
        logout: (state) => {
            state.currentUser = null
        }
    }
})

export const { loginStart, loginSuccess, loginFailure, logout } = userSlice.actions
export default userSlice.reducer;

2

Answers


  1. You can access the store outside a component by importing it and calling the getState method.

    Be careful that importing the store often leads to circular dependencies, there is a redux FAQ page about this.

    I personally import the store in combination with an axios interceptor to modify the headers before every request (because setting the header in axios.create won’t work if the token changes). I add my interceptors in index.js and not in the same module where I declared the axios instance just to avoid circular import dependency errors (that will happen as soon as you introduce api calls in redux async thunks etc.)

    Login or Signup to reply.
  2. you can only use hook in react functional component

    and useSelector is a hook

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search