1
0

More than 1 year has passed since last update.

【React】外部APIからデータを取得して表示する方法

Posted at

はじめに

 本記事は、プログラミング初学者が、学習を進めていて疑問に思った点について調べた結果を備忘録も兼ねてまとめたものです。
 そのため、記事の内容に誤りが含まれている可能性があります。ご容赦ください。
 間違いを見つけた方は、お手数ですが、ご指摘いただけますと幸いです。

外部APIからデータを取得して表示する方法

Reactで、外部APIからデータを取得して表示するには、fetch()を使用し、以下のように記述します。

// Hookを使用しない場合
componentDidMount(){
        fetch("APIのURL")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    character: data,
                    loading: false
                })
            })
           .catch(error => {
             console.error(error)
           }
        }


// Hookを使用した場合
 useEffect(() => {
     fetch("APIのURL")
            .then(response => response.json())
            .then(data => {
                this.setState({
                    character: data,
                    loading: false
                })
            })
           .catch(error => {
             console.error(error)
           }
        }, [])

fetchメソッドはComponentDidMount内で行います。

fetch(APIのURI):APIを取得する

.then(response => response.json()):データ取得完了後、取得したPromise型の値をオブジェクト化

.then(data => …):「…」に必要な処理を記述

.catch(): エラーの場合の処理を記述

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