Two suggestions:
- Determine if
response
contains any data before logging it.
- Move your
fetchData
function into the useEffect
hook. https://stackoverflow.com/a/56851963/8943092
Below is an example of how you can test for the existence of data, and here is a live Sandbox.
Note that we use a simple conditional to check if (myData)
is truthy. Our useState hook sets no default value, so the conditional returns true
once data is present.
In the render method, we use a ternary to check for the existence of data.
Your solution may be slightly different because you set the default value of user
to an empty array []
. Assuming your API call returns an array, you'll test for data with if (user.length > 0)
.
import React, { useEffect, useState } from "react";
export default function App() {
const [myData, setMyData] = useState();
useEffect(() => {
function fetchData() {
setTimeout(function () {
setMyData("I am user data");
}, 3000);
}
if (myData) {
console.log(myData);
} else {
console.log("No data yet");
}
fetchData();
}, [myData]);
return (
<div className="App">{myData ? <p>{myData}</p> : <p>No data yet</p>}</div>
);
}