next.js swr I do not want to execute it only at the time of initial drawing

1.2k views Asked by At

Development Enviroment
・ next.js
・ typescript
・ swr

it uses swr to communicate with swr.
I want to run it only when the value of the query is changed.
but is also executed during the initial drawing.
what can I do to prevent it from running during the initial drawing?

export const useUserQuery = (query: string) => {
  const fetcher = (url) => {
    Axios.get(url).then((res) => {
      return res;
    });
    const path = `users/?query=${query}`;
    const { data, error } = useSWR<IUser>(path);
    return {
      data: data,
      loading: !error && !data,
      Error: error,
    };
  };
};
2

There are 2 answers

2
tobzilla90 On

UPDATED:

use initalData and disable revalidateOnMount then it should work as you expect.

see more in the docs: https://github.com/vercel/swr

0
Jakov Gl. On

It seems that you what to refeatch on variable change. If you try this, it won't work, because even if token changes, SWR will still use the same key and return the wrong data.

useSWR('/api/user', url => fetchWithToken(url, token))

Instead, you can use an array as the key parameter, which contains multiple arguments of fetcher:

const { data: user } = useSWR(['/api/user', token], fetchWithToken)

See more in docs