Skip to content

deferFn child component calls run in useEffect doesn't trigger data update #332

Open
@MenchieYoung

Description

@MenchieYoung

Not sure if this a issue in useAsync, or expected, we have encountered this problem:

export const getCarInfo: DeferFn<
  CarInfo
> = async (args: any[]) => {
  const params1 = args[0];
  const params2 = args[1];
  const params3 = args[2];

  const resp = await fetchData.get({
    url: GET_CAR_INFO
    config: {
      timeout: 20000,
      params: {
        params1,
        params2,
        params3,
      },
    },
  });
  console.log("resp.data: ", resp.data);
  return resp.data as CarInfo;
};
export const useCarInfo = (): {
  getCarInfoPending: boolean;
  getCarInfoError: Error | undefined;
  carInfo: CarInfo | undefined;
  runGetCarInfo: (...args: any[]) => void;
} => {
  const { data, error, isPending, run } = useAsync({
    deferFn: getCarInfo,
  });

  console.log("isPending: ", isPending);
  console.log("error: ", error);
  console.log("data: ", data);

 return {
    getCarInfoPending: isPending,
    getCarInfoError: error,
    carInfo: data,
    runGetCarInfo: run,
  };
};
export const ParentComponent = () => {
  const {getCarInfoPending, getCarInfoError, carInfo, runGetCarInfo} = useCarInfo();

  return (
    <ChildComponent runGetCarInfo={runGetCarInfo} />
  )
}
export const ChildComponent = ({runGetCarInfo}: {runGetCarInfo: (...args: any[]) => void;}) => {
  useEffect(() => {
     runGetCarInfo('Robin', 'CA', '2023-03-21');
  }, []);

  return <div />;
}

The thing is, I can see the log resp.data: has valid output, but the log - isPending is always false, and error data is always undefined.

isPending:  false
error:  undefined
data:  undefined

isPending:  false
error:  undefined
data:  undefined

resp.data:  {carInfoList: Array(3)}

And once I move useEffect to ParentComponent, or useCarInfo hook, everything works as expected and isPending can become true, data/carInfo will have valid value.

isPending:  false
error:  undefined
data:  undefined

isPending:  true
error:  undefined
data:  undefined

resp.data:  {carInfoList: Array(3)}

isPending:  false
error:  undefined
data:   {carInfoList: Array(3)}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions