Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda