Reputation: 23
function Header(props) {
const [ serverData, setServerData ] = useState({});
fetch('http://localhost:4001/api')
.then(res => res.json())
.then((data) => {
setServerData(data);
console.log(data);
});
return (
<div>{serverData}</div>
);
}
I'm trying to make this functional React component to get data from express api.
My code editor keep shutting down, I think that receiving data part is in the loop.
How can I make this functional component to fetch the data just once, without using componentdidmount or class type component.
I tried useCallback, it did not work for me..
Upvotes: 1
Views: 134
Reputation: 6169
Use useEffect hook if you want to do this. If will happen once unless the dependencies change (no dependencies listed here).
function Header(props) {
const [ serverData, setServerData ] = useState({});
useEffect(() => {
fetch('http://localhost:4001/api')
.then(res => res.json())
.then((data) => {
setServerData(data);
console.log(data);
});
}, []);
return (
<div>{serverData}</div>
);
}
Upvotes: 1