Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper async await syntax for fetching data using useEffect hook in React? [duplicate]

I have used async for anonymous function inside useEffect hook. I have done this so that I can await for the response that I am fetching. Although this is working fine, I've read somewhere on the web that it is a bad practice to write async await inside useEffect hook like this without any proper explaination for it. So just wanted to ask you guys if this is a good practice or bad practice. If it is a bad practice, then what is the disadvantage of writing async await like this in useEffect, and also wanted to know an alternative for this. Big THANKS for your time and help.

import { useEffect, useState } from "react";

export default function FetchPractice() {
  const [apiData, setApiData] = useState([]);

  useEffect(async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    const data = await response.json();
    setApiData(data);
  });

  return (
    <>
      {apiData.map((post) => (
        <div
          key={post.id}
          style={{
            border: "1px solid black",
            margin: "16px",
            padding: "16px",
            backgroundColor: "#2d2d2d",
            color: "white",
            fontWeight: "bold",
          }}
        >
          {JSON.stringify(post)}
        </div>
      ))}
    </>
  );
}

1 Answers

You should not make your useEffect function async, but you can create an async function inside useEffect

useEffect(() => {
    const getDatas = async () => {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
        const data = await response.json();
        setApiData(data);
    }
    getDatas()
});

or even

useEffect(() => {
    (async () => {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
        const data = await response.json();
        setApiData(data);
    )()
});
like image 157
dbuchet Avatar answered Dec 04 '25 22:12

dbuchet