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

176
Vistas
Context with data from url

I'm trying to make a spotify stats app and I'm trying to make a context to save the token that the app gives you in the url when the user logs in.

TokenContext.js:

import React, { useEffect, useState } from "react";

// token is the state
// logOut and logIn is a function for changing the state.
export const TokenContext = React.createContext({
    token: "",
    logOut: () => { },
    logIn: () => { }
});

function getInitialState() {
    const token = localStorage.getItem('token')
    return token ? token : ""
}

const TokenContextProvider = (props) => {

    const [token, setToken] = useState(getInitialState);

    // Use Effect for getting the token form the url and saving it in the local storage
    useEffect(() => {
        const hash = window.location.hash
        let _token = window.localStorage.getItem("token")

        if (!_token && hash) {
            _token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]

            window.location.hash = ""
            window.localStorage.setItem("token", _token)
        }
        setToken(_token)


    }, [])

    const logIn = (token) => {
        setToken(token);
    };

    const logOut = () => {
        setToken("")
        window.localStorage.removeItem("token")
    }

    return (
        <TokenContext.Provider
            value={{ token: token, logOut: logOut, logIn: logIn }}
        >
            {props.children}
        </TokenContext.Provider>
    );
};

export default TokenContextProvider;

The problem is that the useEffect hook isn't working because it is not saving the token in the local storage and the url keeps the same when the user already logged in.

Example of how the url stays: http://localhost:3000/#access_token=BQA4OEmPw6VRknPFNW9Z2dS-uGZHbEJ3WbAWJy-jmsLFEy_PWMgMMfMYKqAQKdNgd6j1FDPIKYTNlztx2L1IgwC_gLvee-xx0hj8rKOVgDVtN1NktbhV4sHRtuzK_1EaRNGjrzxvkvXqdQ3jd0NiD4mHzd1uWC2udWTXejHDXHf9x8K3MxZGIQ&token_type=Bearer&expires_in=3600

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

0

useEffect runs only once (when the context provider is mounted) - are you sure that the URL already contains the access token at that time?

Maybe you just need to add a dependency to your effect that will cause the effect to re-run when the URL changes as described here.

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