Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

reactjs - how to call `localStorage.getItem ` immediately after render

first i use localStorage.setItem to save a token that i've taken from api and set it as header in my axios

i need to use local.storage.getItem() to read the data and then set it as header
so there is another action which sends request ,takes the token and saves it to local storage by localStorage.setItem() and replaces the browser history to where i'm calling the action that needs the token ,but it shows 404 error with the only first error which means only at the first time and if i close the page and open it again it works fine
I'll show the code step by step

here is my code where i want to use the token

import axios from 'axios';
const token =  localStorage.getItem('token')//here doesn't get it and shows 404 error from API i refresh the page for second time or after 
export default axios.create({

  headers:{"Authorization": `Bearer ${token}`}
})

here is my action where i get the token with diffrent instance of axios which has no header

export const sendCode = (phone, code) => async dispatch => {
  dispatch({ type: LOADING_STATE })

  const response =
    await loginApi.post(baseurl + "Auth/Checkcode", {
      phone: phone,
      code: code
    },
    )
  dispatch({ type: SEND_CODE, payload: response.data });
  if (response.data.success === true) {
    history.replace('/home')
   localStorage.setItem("token", response.data.obj.token)
  }

and finally here is the action that i call it with the instance that has header

export const getHomeInfo = () => async dispatch => {
  dispatch({type:LOADING_STATE})
 const response = await homeAPI.get(baseurl + "Home/GetList")//homeAPI is the instance that has header

  dispatch({ type: GET_HOME_INFO, payload: response.data })
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import axios from 'axios';
const token =  localStorage.getItem('token')
export default axios.create({

  headers:{"Authorization": `Bearer ${token}`}
})

Here, token will be fetch once when the js file is bundled, you have to refetch it each time :

import axios from 'axios';


const getHeaders = () => {
  const token = localStorage.getItem('token')
  return {"Authorization": `Bearer ${token}`}
}

export default axios.create({
  headers: getHeaders()
})

EDIT : The code above does not work since axios.create() is called only once, if you need dynamic headers, you should add an interceptor which will be called before each request :

const axiosInstance = axios.create()

axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error),
);

export default axiosInstance

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...