【问题标题】:How can I use SWR hook for all API methods? (CRUD)如何对所有 API 方法使用 SWR 挂钩? (克鲁德)
【发布时间】:2022-06-11 14:50:15
【问题描述】:

我正在切换过去通过令牌提供的某些 CRUD 功能,但现在我正在使用 SWR,但我不知道如何转换它。 我将这个钩子用于 GET 方法,但对于其他方法,我不知道该怎么做!

export default function useGetData(apiKey) {
const fetcher = async (...args) => await fetch(...args).then(res => res.json());
const { data, mutate, error } = useSWR(apiKey, fetcher);

const loading = !data && !error;

return {
    loading,
    user: data,
    mutate
}
}

【问题讨论】:

    标签: reactjs react-hooks next.js swr


    【解决方案1】:

    好的,我找到了答案:

      export default function useGetData({ url, payload, options = {} }) {
      const fetcher = async () => {
        const options = {
          method: payload ? 'POST' : 'GET',
          ...(payload && { body: payload }),
          headers: {
            accept: 'application/json',
            'Content-Type': 'application/json',
          },
        };
    
        return await fetch(url, options).then((res) => res.json());
      };
      const defaultOptions = { revalidateIfStale: false };
      const { data, mutate, error, isValidating } = useSWR(url, fetcher, {
        ...defaultOptions,
        ...options,
      });
      const loading = !data && !error;
      return { data, loading, mutate, isValidating };
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2022-07-16
      • 1970-01-01
      • 2021-01-24
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多