Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
I tried to add userinfo to localstorrage but it didnt work

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' })
    }
})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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'))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda