Multiple fetch data axios with React Hooks

前端 未结 4 1985
忘掉有多难
忘掉有多难 2021-01-03 13:53

I would like to get global information from Github user and his repos(and get pinned repos will be awesome). I try to make it with async await but It\'s is correct? I\'ve go

4条回答
  •  无人及你
    2021-01-03 14:16

    Figured I'd take a stab at it because the above answer is nice, however, I like cleanliness.

    import React, { useState, useEffect } from 'react'
    import axios from 'axios'
    
    const Test = () => {
        const [data, setData] = useState([])
    
        useEffect(() => {
            (async () => {
                const data1 = await axios.get('https://jsonplaceholder.typicode.com/todos/1')
                const data2 = await axios.get('https://jsonplaceholder.typicode.com/todos/2')
                setData({data1, data2})
            })()
        }, [])
    
        return JSON.stringify(data)
    }
    
    export default Test
    

    Using a self invoking function takes out the extra step of calling the function in useEffect which can sometimes throw Promise errors in IDEs like WebStorm and PHPStorm.

提交回复
热议问题