I'm a bit new in react hooks and effects and I'm having trouble in using useEffect
useEffect( _ => {
(async _ => {
const res = await axios.get('/api/laf/getreportlostitem');
getReports(res.data);
setLoading(false);
})();},[reports]);
The code above is a useEffect I build to get all the data in the database using axios, and the I put all the data in a state called reports.
// Data State for getting the reports
const [reports, getReports] = useState([]);
but when I console.log the reports, it causes an infinity loop. I dont know why?
Let me show you a brief actions I made.
I'm doing a button that when it has been clicked, the status of the report by its id will be updated.
<Button onClick={ _ => setAsFound(row.id)} variant="contained" color="primary">Set as found</Button>
|
<ClaimedButton onClick={ _ => setAsClaimed(row.id)} variant="contained" color="primary">
Set as claimed
</ClaimedButton>
This is a sample draft of what is the structure of the reports in the state.
{ name, src, yr, campus, department, course, details, contact, status }
As you can see, there's a "status" data in the object. So when I click one of the buttons, the data in the reports state will be updated. Here is the onclick functions of the buttons.
const setAsFound = id => {
if(window.confirm("Are you sure this report item is now found?") ){
const updateStatusFound = {
status: foundData
};
props.setReportToFound(id, updateStatusFound);
}
};
const setAsClaimed = id => {
if(window.confirm("Are you sure this report item is now claimed?")){
const updateStatusClaimed = {
status: claimedData
};
props.setReportToClaimed(id, updateStatusClaimed);
}
};
The founData and claimedData value is this.
const [foundData, setFoundData] = useState('Found, Not Claimed');
const [claimedData, setClaimedData] = useState('Found and Claimed');
This are just values of state that will be sent in the database once the action is complete.
The other codes is just the actions and functions I've working on. But my main concern is why does the reports state causes an infinite loop even the data just rendered in the component? I even have a dependency so that when the datas are updated, the reports state will be updated and it will re render the data. I've tried not including the reports as a dependency. But the problem is that when I remove it, the data does not update. Any ideas how I can stop the infinity loop?