1 year ago

#307731

test-img

M.Pogorzelski

React custom hook with callback parameter not picking up parameter change

I have a following generic custom hook. What I want to achieve is that hook itself exposes api with api functions, which I can use in a callback. I also want a hook to be dependent on a api function parameters changes.

export const useArticleApi = <TResult>(
    callback: (committedOrderApi: ArticlesApi) => Promise<TResult>
): {
    loading: boolean;
    data: TResult | undefined;
} => {
    const callbackRef = useRef<(articlesApi: ArticlesApi) => Promise<TResult>>();
    const [data, setData] = useState<TResult | undefined>();
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        callbackRef.current = callback;
    }, [callback]);

    useEffect(() => {
        (async () => {
            setLoading(true);
            const response = await apiCallWithErrorHandling(
                async () => callbackRef.current && (await callbackRef.current(articlesApi))
            );
            if (response.isSuccess) {
                setData(response?.data);
                setLoading(false);
            }
        })();
    }, [callback]);

    return { loading, data };
};

Hook usage:

const getArticlesForAllCategoriesCallback = useCallback((api: ArticlesApi) => api.getArticlesForAllCategories(
        categories.map(c => ({ id: c.id, name: c.name, pageId: c.pageId }))
), [categories]);

const { data, loading } = useArticleApi<ArticleSearchBarViewData>(api => getArticlesForAllCategoriesCallback(api));

I missing something pretty obvious, but for some reason useEffect inside the hook doesn't detect the change of callback parameter and api method is run only once. Can you spot the issue?

reactjs

react-hooks

use-effect

react-usecallback

0 Answers

Your Answer

Accepted video resources