Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
MenchieYoung opened this issue Jul 3, 2023 · 0 comments

Comments

@MenchieYoung
Copy link

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)}
@MenchieYoung MenchieYoung changed the title deferFn child component calls run doesn't trigger data update in parent components deferFn child component calls run in useEffect doesn't trigger data update Jul 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant