Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional rendering wont register change in object ReactJS

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 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");
    }
  };

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

After each render userDetailsObj will take that value from localStorage. Which is why you have this behavior. You can overcome 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");
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading