Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react js localstorage value object [duplicate]

I save what I get from my backend to a local storage:+

   async onSubmit(e){
        e.preventDefault();
        const {login, password } = this.state;

        const response = await api.post('/login', { login,password });
        const user = response.data.user;
        const {jwt} = response.data;
        console.log(user);
        localStorage.setItem('token', jwt);
        localStorage.setItem('user', user);
        this.props.history.push("/home");
    }

my

const user = response.data.user;

return this:

{id: 2, name: "spt", email: "email", login: "spt", password: "$2a$10$Rqc1VU1TfKD6MypNzbgemeR0O4YeXIFy1XiURjNeHk0gpWJitp4da", …}

two object [object object]

like image 379
Felipe Avatar asked Jun 13 '26 05:06

Felipe


1 Answers

Local Storage is key-value storage where key is string and value is string also.

You must stringify your data, you can do this

localStorage.setItem('user', JSON.stringify(user));

And get it like

const user = JSON.parse(localStorage.getItem('user'));
like image 180
svltmccc Avatar answered Jun 14 '26 17:06

svltmccc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!