How to call an async function inside a UseEffect() in React?

后端 未结 4 1584
终归单人心
终归单人心 2020-12-02 01:39

I would like to call an async function and get the result for my UseEffect.

The fetch api examples i found on the internet are directly made in the useEffect functio

相关标签:
4条回答
  • 2020-12-02 02:08

    If you're invoking it right-away you might want to use it as an anonymous function:

    useEffect(() => {
    
      (async () => {
         const data = await getData(1);
         setData(data);
      })();
    
    }, []);
    
    0 讨论(0)
  • 2020-12-02 02:14

    It would be best if you did what the warning suggests - call the async function inside the effect.

    function blabla() {
        const [data, setData] = useState(null);
    
        useEffect(() => {
            axios.get(`http://url/api/data/1`)
             .then(result => {
                setData(result.data);
             })
             .catch(console.error)
        }, [setData]);
    
        return (
            <div>
                this is the {data["name"]}
            </div>
        );
    }
    
    0 讨论(0)
  • 2020-12-02 02:14

    You can still define the async function outside of the hook and call it within the hook.

    const fetchData = async () => {
       const data = await getData(1);
       setData(data);
    }
    
    useEffect(() => {
      fetchData();
    }, []);
    
    0 讨论(0)
  • 2020-12-02 02:21

    Create an async function inside your effect that wait the getData(1) result then call setData():

    useEffect(() => {
      const fetchData = async () => {
         const data = await getData(1);
         setData(data);
      }
    
      fetchData();
    }, []);
    
    0 讨论(0)
提交回复
热议问题