简体   繁体   中英

Rerendering a component using useState - ReactJS, Axios

When the conditional rendering is triggered I would like to rerender the component. I figure the best option is using useState.

  const canBookSlot = (id) => {
    if (userDetailsObj.canBook != 0) {
      Axios.post("http://localhost:3001/api/book/week1/ex", {
        room: userDetailsObj.room,
        id: id.id + 1,
      });
      setSlotsList(...slotsList); //This doesn't work
      console.log("booked");
    }
 };

After the Axios method the database is updated and therefore the setSlotList should be updated? I thought this was the purpose of useEffect:

 const [slotsList, setSlotsList] = useState([]);

    useEffect(() => {
    Axios.post("http://localhost:3001/api/get/week1/ex").then((response) => {
      setSlotsList(response.data);
    });
}, []);¨

in first snippet

Axios.post("http://localhost:3001/api/book/week1/ex", {
        room: userDetailsObj.room,
        id: id.id + 1,
      });

is async funntion, you should add await before it or handle through .then() then setSlotsList(...slotsList); will rerender component after resolve that promise. Second thing is in you next snippet: useEffect with empty deps will trigger only once - when component did mount.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM