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

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

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

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