Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
How do I add a JS state variable of 1 React component for use in other components?

I have a Home.js component that signs the user up to the API and logs in and then gets the token received from the response authorization header and saves it in the state 'token' variable.

This token will be used in all other components to access the API when requests are made, so what is the best way of using this value for all other components?

Home.js:

   const SIGNUP_URL = 'http://localhost:8080/users/signup';
    const LOGIN_URL = 'http://localhost:8080/login';
    class Home extends Component {
    
        constructor(props) {
            super(props);
            this.state = {
                isAuthenticated:false,
                token: ''
            };
        }
        
        componentDidMount() {
            const payload = {
                "username": "hikaru",
                "password": "JohnSmith72-"
            };
            fetch(SIGNUP_URL, {
                method: 'POST',
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(payload)
            })
                .then(response => response.json())
                .then((data) => {
                    console.log(data);
                });
            fetch(LOGIN_URL, {
                method: 'POST',
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(payload)
            })
                .then(response =>
                    this.setState({token: response.headers.get("Authorization"), isAuthenticated:true})
                )
    
        }

For example the userList component which will fetch the user data from the API, but requires the API token stored in the Home component's token state variable to send the request successfully via the authorization header.

Thanks for any help

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You should be using AuthContext and localStorage to do this, save the token in the state or localStorage and make a config file which uses the same token when calling an api i have done it in axios. Axios has a concept of interceptors which allows us to attach token to our api calls, Im saving the token in the localStorage after a successfull login and then using the same token from localStorage to add to every call which needs a token, if the api doesnt need a token (some apis can be public) i can use axios directly, check out the below code:

import axios from 'axios';

let apiUrl = '';
let imageUrl = '';
if(process.env.NODE_ENV === 'production'){
    apiUrl = `${process.env.REACT_APP_LIVE_URL_basePath}/web/v1/`;
}else{
   apiUrl = `http://127.0.0.1:8000/web/v1/`;
}

const config = {
    baseURL: apiUrl,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "https://www.*******.com",
        'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE',
    },
};

const authAxios = axios.create(config);

authAxios.interceptors.request.use(async function(config) {
    config.headers.Authorization = localStorage.getItem('access_token') ?
        `Bearer ${localStorage.getItem('access_token')}` :
        ``;
    return config;
});

export { apiUrl, axios, authAxios };

now on making api call u can do something like below:

import { apiUrl, authAxios } from '../config/config'

export async function saveAssignment(data) {
    try {
        const res = await authAxios.post(apiUrl + 'assignment/save-assignment', data)
        return res.data;
    }
    catch(e){
        
    }
}

here pay attention im not using axios to make api call but using authAxios to make calls(which is exported from the config file) which will have token in the header.

(You can also use a third party library like Redux but the concept remains the same)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can create a custom function called authenticated_request for example. This function could fetch your token from the CookieStorage in case of web or async storage in case of react-native or even if you have it in some state management library. Doesn't matter. Use this function instead of the fetch function and call fetch inside it. Think of it as a higher order function for your network requests.

const authenticated_request(url, config) {
  fetch(url, {
    ...config,
    headers: {
      ...config.headers,
      Authorization: getToken()
    }
  });
}

You can also leverage the usage of something like axios and use request interceptors to intercept requests and responses. Injecting your token as needed.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can place the token into a cookie if your app is SSR. To do that, you have to create the following functions:

export const eraseCookie = (name) => {
    document.cookie = `${name}=; Max-Age=-99999999;`;
};

export const getCookie = (name) => {
    const pairs = document.cookie.split(';');
    const pair = pairs.find((cookie) => cookie.split('=')[0].trim() === name);
    if (!pair) return '';
    return pair.split('=')[1];
};

export const setCookie = (name, value, domain) => {
    if (domain) {
        document.cookie = `${name}=${value};path=/`;
    } else {
        document.cookie = `${name}=${value}`;
    }
};

You can also place your token into the local storage:

Set into local storage via built-in function:

localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c');

Get the token via built-in function:

const token = localStorage.getItem('token');
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda