Harshit
Harshit

Reputation: 11

Error in setting headers in axios and react

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

Upvotes: 0

Views: 78

Answers (1)

Shri Hari L
Shri Hari L

Reputation: 4894

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.

Upvotes: 1

Related Questions