I'm trying to rebuild some class components I have as functional components using React hooks to do the fetch.
I can fetch the data, this is fine, but it's calling to my API every few milliseconds, I just want it to fetch the data and stop as it would have in the class component with componentDidMount.
I think I can see why it's doing it (the fetchData() inside the function means it will just keep calling itself) but I'm not sure how to fix it.
I tried adding a setInterval, changing the order, and moving the fetchData() outside the function (the component wouldn't render because it was then undefined).
const MyFunction = () => {
const [apiResponse,setApiResponse] = useState({})
async function fetchData() {
const res = await fetch(`http://localhost:9000/example`,{
method: 'POST',
mode: 'cors',
body: JSON.stringify({date: '20190707'}),
headers: {'content-type': 'application/json',
credentials: 'include'
}
})
res
.json()
.then(res => setApiResponse(res))
}
useEffect(() => {
fetchData();
});
var queryResult = apiResponse['units']
return (
<React.Fragment>
<CardHeader color={"info"} stats icon>
<CardIcon color={"info"}>
<Icon>{"trending_up"}</Icon>
</CardIcon>
<p className={''}>Drop In</p>
<h3 className={''}>
{queryResult} <small>Units</small>
</h3>
</CardHeader>
<CardFooter ></CardFooter>
</React.Fragment>
);
}