2

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?

0

3 Answers 3

4

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)}
Sign up to request clarification or add additional context in comments.

Comments

1

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)}

Comments

1

I assume that clicking the "refresh" button is supposed to reload the data for 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}         
>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.