Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda