Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!