Search code examples
reactjsuse-effectuse-statereact-functional-component

Calling a function after updating the state more than 1 time


I am storing some data in the state. I first call 1 API and get the update the data in the state 3 times. After the data update, I have to call another API using the updated state data. I am unable to do so . If the state was updated just once, I would have use useEffect. But, here it is changing 3 times.

const [data, setData] = useState(() => getDataInit());


const setDataKey = key => value =>
  setData(d => ({
    ...d,
    [key]: value,
}));

const postFn = () => {
  const response = await updateData({ body: data });
  onSave({
    response,
    widget,
    wrapperId,
  });
};

const resetFn = () => {
  const defaultData = await getDefaultData({
    query: { id: data.default_id },
  });
  setDataKey('quantity')(defaultData.quantity);
  setDataKey('name')(defaultData.name);
  setDataKey('amount')(defaultData.amount);
  postFn();
};

Solution

  • You can update to call only one setData. So you can add useEffect to call postFn

    const resetFn = () => {
      const defaultData = await getDefaultData({
        query: { id: data.default_id },
      });
    
      const newData = {
       quantity: defaultData.quantity,
       name: defaultData.name,
       amount: defaultData.amount,
      };
    
      setData((d) => ({
        ...d,
        ...newData,
      }));
    }
    
    useEffect(() => {
      postFn();
    }, [data]);