Home > Software engineering >  How can I save logged users email in react
How can I save logged users email in react

Time:05-27

I have this login API. i wan't to save logged users email in state or something else. so I can show it on header after the login. user email is in the data.email .

login.tsx


    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL   `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                router.push("/Home");
            }
        }, (err) => {
            console.log(err);
        })
        
    }
    return {
        LoginAuth,
    }
}

CodePudding user response:

You can use Context API, and wrap your whole React app inside it. That way you can access these details from anywhere in your app.
Context API doc

CodePudding user response:

There are a couple of ways of achieving this:

  1. You can simply have a state, that's accessible, but most likely you are using different components:
  2. You can employ useContext. This will allow to share the state
  3. If you want the email to be persistent between session then you could use localstorage and set a context at app start.
  • Related