Home > Blockchain >  I tried to add userinfo to localstorrage but it didnt work
I tried to add userinfo to localstorrage but it didnt work

Time:03-16

Hello guys i want help running this code because i try my best and i didnt find a solution. i want to add the user info entered from the form to the localstorage so i can use them later for the active session until logging out. here the code below

here is the register js file :

async function registerUser(event) {
    event.preventDefault()

    const response = await fetch('http://localhost:2090/api/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        role,
        name,
        email,
        password,
      }),
    })

    const data = await response.json()

    if (data.status === 'ok') {
      localStorage.setItem('user', data.user)
      navigate('/login')
    } else {
      alert('User already exists !!')
    }
  }

and here is the register api from server indexjs file:

app.post('/api/register', async (req, res) => {
    console.log(req.body)
    try {
        const user = await User.create({
            role: req.body.role,
            name: req.body.name,
            email: req.body.email,
            password: req.body.password,
        })
        res.json( { status: 'ok' , user: user })
    }catch (err) {
        res.json({ status: 'error', error: 'Duplicate email' })
    }
})

CodePudding user response:

Hey it's slightly unclear where the issue is but incase your issue is with getting the user data from localStorage, I'll write this here:

localStorage is only able to store String, so all non-string types need to be cast to string before they are saved in localStorage. When an object is implicitly cast to string, it returns [object Object].

If you want to store an object in there, your best bet is to deserialise it with JSON.stringify and the serialise it again whenever you want to access it with JSON.parse:

Example

const user = { id: 'test-id' };

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

const userFromStorage = JSON.parse(localStorage.getItem('user'));

console.log(userFromStorage); // { id: 'test-id' }

You might want to wrap JSON.parse() in a try/catch block incase the user isn't set or the stored object is malformed since it will throw an error.

CodePudding user response:

you have to convert to the string and only store to the localstorage as json data is not supported by localstorage and sessionstorage using

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

and retrieve the data and parse using

JSON.parse(localStorage.getItem('user'))

  • Related