🚀

useSWR時にparameterを送る

2023/03/06に公開

概要

  • swrリファレンス通りにやってみてもどうにも上手くいかなかったので🥺
  • 各バージョン
package.json
{
    "dependencies": {
        "axios": "^1.3.4",
        "react": "^18.2.0",
        "swr": "^2.0.3",
        "typescript": "^4.9.5",
      },
    "devDependencies": {
       "msw": "^1.1.0",
    }
}

本題

api.ts
import { type AxiosInstance } from "axios";

const apiClient: AxiosInstance = axios.create({
  baseURL: "http://localhost:3000",
  headers: { "Content-Type": "application/json" },
});

export { apiClient };

fetcher.ts
import { type AxiosResponse } from "axios";
import { apiClient } from "./api";

interface IProps {
  url: string;
  params: object;
}

const fetcheWithParams = async <T>(props: IProps): Promise<T> =>
   await apiClient
    .get(props.url, {
      params: {
        ...props.params,
      },
    })
    .then((res: AxiosResponse<T>) => res.data);

export { fetcheWithParams };
swr.ts
import useSWR from "swr";
import { fetcheWithParams } from "./fetcher";

const { data, error  } = useSWR<I〇〇, Error>(
    {
      url: "/info",
      params: {
        testId: 1,
	testText: "test"
      },
    },
    fetcheWithParams
  );

余談

  • MockServiceWorkerを利用している場合は下記のように受け取ります🕊️
handler.ts
import { rest } from "msw";

export const handler = [
  rest.get("/info", (req, res, ctx) => {
    const testId = req.url.searchParams.get("testId");

    return res(ctx.status(200), ctx.json(testId));
  }),
];

Discussion