0

I have tried many of the stack overflow solution but I am unable to solve this problem

My code is below

helper/axios.js

import axios from "axios";

const instance = axios.create({
  baseURL: process.env.REACT_APP_BACKEND_URI,
  timeout: 1000,
  headers: {},
});

export default instance;

App.js

import axios from "./helper/axios";
 
const { user } = useAppSelector((state) => state);

axios.interceptors.request.use((config: any) => {
    if (user.isLoggedIn) {
      config.headers.authorization = user.accessToken;
      config.headers["x-refresh"] = user.refreshToken;
      console.log(config);
    }
    return config;
  });

[Image of console] [1]: https://i.sstatic.net/fWAIb.png

1 Answer 1

1

Maybe you could try importing your store directly inside the file.

I don't thing useSelector can be called outside the Functional Component.

Example,

import axios from "./helper/axios";
import store from "./your_path_to_store_file"

axios.interceptors.request.use((config: any) => {
    const { user } = store.getState();
    if (user.isLoggedIn) {
      config.headers.authorization = user.accessToken;
      config.headers["x-refresh"] = user.refreshToken;
      console.log(config);
    }
    return config;
});

By doing so, we might get the latest value from the store.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that . But the following error occur "React Hook "useAppSelector" cannot be called inside a callback"
Edit the answer. Try it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.