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

206
Vistas
React, conditional rendering wont register change in object

The if statement in canBookSlot() is only checked once for some reason. The second time canBookSlot() is triggered, the userDetailsObj.canBook should be 0 after running updateUser(). And according to the console log it is the case, but the if statement still runs, why?

let userDetailsString = localStorage.getItem("userDetails");
let userDetailsObj = JSON.parse(userDetailsString);

const updateUser = () => {
  userDetailsObj["hasBooked"] = 1;
  userDetailsObj["canBook"] = 0;
};

const canBookSlot = (id) => {
  if (userDetailsObj.canBook != 0) { // always true
    updateUser();
    Axios.post("http://localhost:3001/api/book/week1/ex", {
      room: userDetailsObj.room,
      id: id.id + 1,
    }).then(() => updateData());
  } else {
    console.log("already booked");
  }
};
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

After each render userDetailsObj will take that value from localStorage. That's how every variable inside a component which isn't a state made with useState hook, or a ref made with useRef hook behaves. You can fix your problem this by using a state, like so:

const [userDetails, setUserDetails] = useState(JSON.parse(localStorage.getItem("userDetails")));
const updateUser = () => {
  const newUserDetails = { ...userDetailsObj, hasBooked: 1, canBook: 0 };
  setUserDetails(newUserDetails);
  localStorage.setItem("userDetails", JSON.stringify(newUserDetails));
};

const canBookSlot = (id) => {
  if (userDetails.canBook != 0) {
    //Always true
    updateUser();
    Axios.post("http://localhost:3001/api/book/week1/ex", {
      room: userDetailsObj.room,
      id: id.id + 1,
    }).then(() => updateData());
  } else {
    console.log("already booked");
  }
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

Can you clarify where this code runs? Are you using a class component or functional component? Would you mind sharing the entire component? If it is doing what I think it is doing, the let userDetailsString = localStorage.getItem("userDetails"); is running every render which means on every render, it grabs the value in localStorage and uses that, rather than using your object stored in userDetailsObj.

If you are using functional components, you could fix this by using state.

  let userDetailsString = localStorage.getItem("userDetails");
  let [userDetailsObj, updateUserDetailObj] = useState(JSON.parse(userDetailsString));

  const updateUser = () => {
    let u = { ...userDetailsObj, 
    hasBooked: 1,
    canBook: 0,
    }
    updateUserDetailObj(u);
  };

If you are using class Components, let me know and I'll update it with that option.

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