nanostores / query

⚡️ Powerful data fetching library for Nano Stores. TS/JS. Framework agnostic.
MIT License
228 stars 10 forks source link

Multiple re-renders | React #53

Closed sitarass closed 3 months ago

sitarass commented 3 months ago

I have implemented a hook fetcher which takes the fetcher's data (@nanostores/query used) from useStore. However, I am observing with console log that the same data is logged multiple times causing a re-render in to the consumer components.

const useData = <T, E>(fetcher: FetcherStore<T, E>) => {
  const { data, error, loading: validating } = useStore(fetcher);
  console.log(data);

  const loading = validating && !data && !error;

  return {
    data,
    error,
    mutate: fetcher.revalidate,
    loading,
    validating,
    actions: {
      invalidate: fetcher.invalidate,
      revalidate: fetcher.revalidate,
      mutate: fetcher.mutate,
    },
  };
};
sitarass commented 3 months ago

Here's how I use the one above

const fetchers = useStore($fetchers);
  const api = fetchers?.[endpoint];

  const fetcher = useMemo<
    FetcherStore<WaveCxmResponse<Response>, WaveCxmResponse<undefined>>
  >(
    () => api(request, !skip, fetchingOptions),
    [api, request, skip, fetchingOptions]
  );

  // It's necessary to keep the fetcher tamed and avoid memory leaks that lead to duplicated requests.
  fetcher?.subscribe(() => {});

  const { data, error, ...rest } = useData(fetcher);

  // @ts-ignore
  const waveError = error?.response?.data as WaveError;

  return {
    data: data?.data,
    // @ts-ignore
    error: error?.response?.data,
    request,
    ...rest,
  };
dkzlv commented 3 months ago

@sitarass I need more information to somehow work out this report 😄 Please, follow the typical structure of steps-expected-actual, and ideally provide an isolated reproduction on StackBlitz/codepen.

Feel free to reopen if there's anything I can help you with.

dkzlv commented 3 months ago

What should I look at here?

sitarass commented 3 months ago

Sorry, I meant to post this comment in another issue