1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

useSWR時にparameterを送る

Posted at

概要

  • 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));
  }),
];

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?