Home > Software design >  Rerendering a component - ReactJS, Axios
Rerendering a component - ReactJS, Axios

Time:07-11

After calling canBookSlot I want to update the slotsList I figure i have to make a new Axios request, can i reuse the useEffect whitin the then() method to rerender the component with updated properties or is there any other smart way of doing it without rewriting the Axios request?

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

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

  const canBookSlot = (id) => {
    if (userDetailsObj.canBook != 0) {
      Axios.post("http://localhost:3001/api/book/week1/ex", {
        room: userDetailsObj.room,
        id: id.id   1,
      }).then(); // update the slotsList
    }
  };

EDIT:

The userDetailsObj is an object from another component, It isn't the same object as the ones in slotList how do i go about rerendering userDetailsObj

    const updateData = () => {
    Axios.post("http://localhost:3001/api/get/week1/ex").then((response) => {
      setSlotsList(response.data);
    });
  }

  useEffect(() => {
    updateData();
  }, []);

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

  const canBookSlot = (id) => {
    if (userDetailsObj.canBook != 0) { // Always true 
      Axios.post("http://localhost:3001/api/book/week1/ex", {
        room: userDetailsObj.room,
        id: id.id   1,
      }).then(() => updateData())
    }
  };

CodePudding user response:

You can create common function and reuse when you want to call that axios api and update the data.

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

useEffect(() => {
 updatedData();
}, []);

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

const canBookSlot = (id) => {
if (userDetailsObj.canBook != 0) {
  Axios.post("http://localhost:3001/api/book/week1/ex", {
    room: userDetailsObj.room,
    id: id.id   1,
  }).then(() => updateData()); // update the slotsList
}
};
  • Related