Home > Software engineering >  Real time updating Axios array
Real time updating Axios array

Time:12-05

imagine having custom hook like this :

import React from "react";
import axios from "axios";
export const useFetchListDetails = () => {
  let token = JSON.parse(localStorage.getItem("AuthToken"));
  const [listDetails, setListDetails] = React.useState();
  const HandleFetchDetails = (idConfer) => {
    axios({
      method: "post",
      url: `${process.env.REACT_APP_API_URL_API_LIST_SERVICECONFER}`,
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      data: JSON.stringify({
        idConfer: parseInt(idConfer),
      }),
    })
      .then((r) => {
        setListDetails(r.data.Data.ListService);
      })
      .catch(() => alert("خطا در شبکه"));
  };
  return { HandleFetchDetails, listDetails };
};

the listDetails is an array with object that I use it to map and return element per each object.

I have a button, and when I click on that button, it deletes selected detail. after this I recall my hook like this:

    <button 
     onClick={() => {
      fetchDelete()
HandleFetchDetails(factor.ID)
     }}
    >Click</button>

now I should have new array, and that means I should have an updated UI but it doesn't. when I console.log r.data.Data.ListService in then. it shows me an updated array but for some reason my listDetails remains the same.

useState is async. I still don't know why this happens.

fetch delete itself is also a custom hook with Axios inside of it. so I also tried to bring the function inside of it. like this:

.then((r) => {
     if (r.data.resCode === 1) {
                  HandleFetchListServiceConfer(
                    ErjaView.ErjaInfo.ID,
                    ErjaView.ErjaInfo.IdPatient
                  );
                  HandleFetchDetails(idConfer);
     
     }
}

it didn't work either.

CodePudding user response:

If I understand correctly, the fetchDelete method should receive a callback that you should invoke only after you got the delete response:

<button onClick={() => fetchDelete({ onSuccess: () => HandleFetchDetails(factor.ID) })} />

and in your delete hook:

const fetchDelete = (options) => {
  callDeleteRequest().then(() => {
    options.onSuccess();
  }
}

This will ensure that you don't suffer from any race conditions between state updates.

  • Related