I tried to build a refresh button to refresh my react-table data, here is my code
const [data, setData] = useState([]);
const [loadingData, setLoadingData] = useState(true);
const [refreshData, setRefreshData] = useState(false);
const getData = async ()=>{
const response = await axios.get('http://localhost:5000/in-data')
setData(response.data)
setLoadingData(false);
}
useEffect(()=>{
getData()
},[refreshData])
Here is the button
<button
className="button"
type="button"
onClick={setRefreshData(!RefreshData)}
>
Refresh
</button>
The result is Error: Infinite Looping, reach the maximum number of re-render. Anyone know how to do it in the proper way?
CodePudding user response:
This is executing the function immediately, not on button click:
onClick={setRefreshData(!RefreshData)}
The result of the function would then be set as the click handler, but since that result is causing a re-render then that point is moot.
You want to pass a function reference as the click handler, not the execution of a function (unless that execution returns the function reference you want, of course). Something like this:
onClick={() => setRefreshData(!RefreshData)}
CodePudding user response:
I assume that clicking the "refresh" button is supposed to reload the data fro the page. So you should do that! In other words, instead of your current approach, you should add a click handler to the button that cals getData()
to fetch the data. refreshData
and setRefreshData()
aren't needed:
<button
className="button"
type="button"
onClick={getData}
>
CodePudding user response:
can you try please putting your function inside of useEffect
useEffect(()=>{
const getData = async ()=>{
const response = await axios.get('http://localhost:5000/in-data')
setData(response.data)
setLoadingData(false);
}
if(refreshData){
getData()
}
},[refreshData])
click on button
onClick={() => setRefreshData(!RefreshData)}