2022-06-19

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=
        >
            {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



No comments:

Post a Comment