0
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.

Reactでポケモン図鑑を作成する(Step1:API通信)

Posted at

はじめに

Reactでポケモン図鑑を作成します。
まずは、基本的なコンポーネントを作るところから入ろうと思います。

成果物

スクリーンショット 2024-02-04 14.36.14.png

ソースコード

ディレクトリ一覧
~/develop/react/react_pokemon (feat/initial)$ tree -I node_modules 
.
├── README.md
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   ├── logo192.png
│   ├── logo512.png
│   ├── manifest.json
│   └── robots.txt
├── src
│   ├── App.tsx
│   ├── api
│   │   └── pokemon
│   │       └── api.ts
│   ├── common
│   │   └── common.ts
│   ├── components
│   │   └── PokemonComponent.tsx
│   ├── index.tsx
│   └── logo.svg
├── tsconfig.json
└── yarn.lock

7 directories, 16 files
src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

// QueryClient インスタンスの作成
const queryClient = new QueryClient();

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
);

ここではTanstackQueryのProviderを定義します。

src/App.tsx
import React from 'react';
import PokemonComponent from './components/PokemonComponent';

function App() {
  return (
    <div>
      <h1>ポケモン表示</h1>
      <PokemonComponent />
    </div>
  );
}

export default App;

src/components/PokemonComponent.tsx
import React from 'react';
import { usePokemon } from '../api/pokemon/api';
import { isNullish } from '../common/common';

const PokemonComponent: React.FC = () => {
  const { data, error, isLoading } = usePokemon('pikachu');

  if (isLoading || isNullish(data)) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h2>{data.name}</h2>
      <p>身長: {data.height}</p>
      <p>体重: {data.weight}</p>
      {data.sprites.front_default ? (
        <img src={data.sprites.front_default} alt={data.name} />
      ) : (
        <div>画像がありません</div>
      )}
    </div>
  );
};

export default PokemonComponent;
src/api/pokemon/api.ts
import { Pokemon } from '@bgoff1/pokeapi-types';
import { UseQueryResult, useQuery } from '@tanstack/react-query';
import axios from 'axios';

export const getPokemon = async (name: string): Promise<Pokemon> => {
  const response = await axios.get<Pokemon>(
    `https://pokeapi.co/api/v2/pokemon/${name}`
  );
  return response.data;
};

// ポケモンデータを取得するカスタムフック
export const usePokemon = (name: string): UseQueryResult<Pokemon, Error> => {
  return useQuery<Pokemon, Error>({
    queryKey: ['pokemon', name],
    queryFn: () => getPokemon(name),
  });
};

src/common/common.ts
export const isNullish = <T>(
  value: T | null | undefined
): value is null | undefined => {
  return value === null || value === undefined;
};

最後に

今回は基盤を整理する事が目的だったので、基本的な事しかやっていません。
次は、検索等を追加していこうと思います。

0
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
0
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?