Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage clears after refresh

For some reason every time I try to save something to my localStorage under the attribute Reservas, if I refresh the page the data in localStorage will be wiped out.

I already used a similar method to store data from the registration form on my app (some other page) and it stores it perfectly. I don't know why this does not work.

$(document).ready(function() {
  var userlog;
  var reserva = {}
  var reservas = []
  var dia_semana_input = document.getElementById('sel_dia')
  var refeicao_input = document.getElementById('sel_tipo')
  var prato_input = document.getElementById('sel_prato')

  var error_fix = {
    nome: "1",
    dia: "1",
    refeicao: "1",
    prato: "1"
  }
  reservas.push(error_fix)
  localStorage.setItem("Reservas", JSON.stringify(reservas));
  var utilizadores = JSON.parse(localStorage.getItem('utilizadores'))
  console.log(utilizadores)
  console.log(reservas)
  reservas = JSON.parse(localStorage.getItem('Reservas'))
  /* verificação para mais tarde utilizar nas reservas*/
  for (var i = 0; i < utilizadores.length; i++) {
    if (utilizadores[i].ativo == 1) {
      userlog = utilizadores[i].Username
    }
  }

  $("#btnReservar").click(function() {
    /*Stores object into array */
    /*which then stores into local storage(?)*/
    var dia_semana = dia_semana_input.value
    var refeicao = refeicao_input.value
    var prato = prato_input.value
    for (var i = 0; i < reservas.length; i++) {
      if (reservas[i].nome == userlog && reservas[i].dia == dia_semana) {
        console.log("primeiro")
        alert('Já existe uma reserva para esse dia!')
      } else {
        console.log("segundo")
        reserva.nome = userlog
        reserva.dia = dia_semana
        reserva.refeicao = refeicao
        reserva.prato = prato
        reservas.push(reserva)
        console.log(reservas)
      }
    }

    localStorage.setItem('Reservas', JSON.stringify(reservas))
  });
})
like image 831
Pedro Ferreira Avatar asked Mar 15 '26 09:03

Pedro Ferreira


1 Answers

You have a call to setItem with that key. That will cause it to be set to the values that are in reservas. Perhaps you want to call getItem?

like image 63
Daniel A. White Avatar answered Mar 16 '26 22:03

Daniel A. White



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!