LoginSignup
8
6

More than 1 year has passed since last update.

【React】fetchを使ってapiからjsonデータを取得する(GETメソッド)

Last updated at Posted at 2021-12-15

今回は簡単にReactでfetchを使って、apiからjsonデータを取得する方法を教える。つまり、GETメソッドの方法。

手順

1. React appを作成

2. Fetch.jsにコード入力

3. App.jsにコード入力

4. 結果

React appを作成

$ npx create-react-app my-app
$ cd my-app
$ yarn build
$ yarn start
  • もし、npmの場合は
$ npx create-react-app my-app
$ cd my-app
$ npm run build
$ npm start

image.png
これで簡単にReact appが成功できた。

Fetch.jsにコード入力

次はsrcの中のFetch.jsファイルを作成し、以下のコードを追加する。
(今回は関数コンポーネントを使っています。)

import React, {useState, useEffect} from 'react'

const Fetch = () => {

    const [posts, setPosts] = useState([])

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts', {method: 'GET'})
        .then(res => res.json())
        .then(data => {
            setPosts(data)
        })
    },[])

    return (
        <div>
            <ul>
                {
                    posts.map(post => 
                    <li key={post.id}>{post.title}</li>
                    )
                }
            </ul>

        </div>
    )
}

export default Fetch;

fetch(' ')の文字列の部分に、叩きたいAPIのURLを記述する。
今回はdummyとして、( https://jsonplaceholder.typicode.com/posts )を使っている。

→ もしlocalhostのAPIの場合、例えば
( http://localhost:3000/posts )の時、package.jsonファイルの中に
"proxy": "http://localhost:3000", を追加し、fetch('/posts')をする必要がある。

fetchメソッドを使う場合、メソッドの指定は{}を使う。今回はGETメソッドなので{method: 'GET'}としておく。
.thenでレスポンスを取得する。

App.jsにコード入力

最後にsrcの中のApp.jsにコードを追加する。

import logo from './logo.svg';
import './App.css';
import Fetch from './components/Fetch';           // ⇦ ここを追加した

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Fetch />                       // ⇦ ここを追加した
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

表示したくないもののコードは削除しても構わない。

結果

以下のように実行したら、成功。🎉

image.png

8
6
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
8
6