3

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]

1
  • Can you please clarify what your question is? Commented Nov 28, 2019 at 19:38

2 Answers 2

11

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'));
Sign up to request clarification or add additional context in comments.

16 Comments

Hello i did that what you said and in contact by socket with my backend i sent const player = JSON.parse (localStorage.getItem ('user')); this.socket.emit ('addPlayer-Queue', player);
But my backend didn't receive this value, if I change the value to 1 for example my backend gets
@Felipe socket take string too, you should not do JSON.parse before sending using socket
Doing this for some reason I don't get this value in the backend
i need make this: const player = localStorage.getItem('user') ?
|
6

localstorage does not support objects. If you want to store the user in localstorage, you need to stringify it: JSON.stringify(user)

If you want to store objects, you could use a third-party NPM module like localforage (not supported in all browsers).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.