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

[useAsyncFn] useCallback won't update due to not adding state to deps #2126

Open
atom-yang opened this issue Sep 17, 2021 · 0 comments · May be fixed by #2545
Open

[useAsyncFn] useCallback won't update due to not adding state to deps #2126

atom-yang opened this issue Sep 17, 2021 · 0 comments · May be fixed by #2545

Comments

@atom-yang
Copy link

atom-yang commented Sep 17, 2021

What is the current behavior?

Not add state to useCallback deps parameter.

const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
const callId = ++lastCallId.current;
if (!state.loading) {
set((prevState) => ({ ...prevState, loading: true }));
}
return fn(...args).then(
(value) => {
isMounted() && callId === lastCallId.current && set({ value, loading: false });
return value;
},
(error) => {
isMounted() && callId === lastCallId.current && set({ error, loading: false });
return error;
}
) as ReturnType<T>;
}, deps);

What is the expected behavior?

Add state to useCallback deps parameter.

const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
    const callId = ++lastCallId.current;

    if (!state.loading) {
      set((prevState) => ({ ...prevState, loading: true }));
    }

    return fn(...args).then(
      (value) => {
        isMounted() && callId === lastCallId.current && set({ value, loading: false });

        return value;
      },
      (error) => {
        isMounted() && callId === lastCallId.current && set({ error, loading: false });

        return error;
      }
    ) as ReturnType<T>;
  }, [...deps, state]);

In most situation, not add state to the deps parameter won't cause any problem. In some rare condition, for example, in our company's project,state won't update in the callback function due to closure, it's really difficult to reappear it in Codesanbox

@NegarYousefian NegarYousefian linked a pull request Feb 28, 2024 that will close this issue
13 tasks
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

Successfully merging a pull request may close this issue.

1 participant