H
H
hamster1410952021-03-16 12:11:44
JSON Web Token
hamster141095, 2021-03-16 12:11:44

How to send token via store in react to agent(axios) file, not via localStorage?

I have a problem. To check user authentication, I must send token Bearer in the headers.
The file with axios settings is in a separate folder
. How can I transfer the token through the application store, and not through localStorage?
Through localStorage I use this:

import axios from 'axios';
import { API_URL } from './constants';

const HTTP = axios.create({ baseURL: API_URL  });

HTTP.interceptors.request.use(
  (config) => {
    const accessToken = localStorage.getItem('access');
    const updatedConfig = { ...config };
    if (accessToken) {
        updatedConfig.headers.Authorization = `Bearer ${accessToken}`;
    }
    return updatedConfig;
  },
  (error) => {
    return Promise.reject(error);
  }
);


Files: 60507603686e5619240292.jpeg

UseApi example:
const [createRoomData, createRoom] = useApi<ICreateRoomDataResponse>({
    method: 'POST',
    url: '/rooms/create',
  });
  useEffect(() => {
    if (createRoomData.response) {
        const data = {
            connectionUuid:createRoomData.response.connection_uuid,
            maxStudentsCount:createRoomData.response.max_students_count,
            maxRoundTime:createRoomData.response.max_round_time,
            maxRoundsCount:createRoomData.response.max_rounds_count,
        }
      dispatch(setRoomData(data));
    }
  }, [createRoomData.response, history, dispatch]);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question