'infinite loop in useEffect when fetch data and set the state
i am setting state inside useEffect but it does not set the state but when i give the same state as a dependency to useEffect it works but it goes to an infinite loop this is my code :
useEffect(() => {
baseUrl.get(`api/get-single-answer-for-manager?user_id=${id}&quizzes_id=${quizzesId}`)
.then((response) => {
setQuizzesName(response.data.quizze_name)
setUser(response.data.user)
const testResult = response.data.data
setTotalTests(response.data.data)
const resultsItem = testResult.map((result) => {
return (
<button key={result.id} id={result.id} onClick={handleClick} className="col-12 col-sm-5 d-flex justify-content-between rounded shadow myButton">
<span id={result.id} className="lesson" >{result.name}</span>
<span id={result.id} className="percentage" >{result.result}%</span>
</button>
)
})
setItems(resultsItem)
setLoading(false)
}).catch((err) => {
console.log(err.response);
})
}, [])
all states are set and work just fine but
setTotalTests(response.data.data)
this part needs a rerender. when i gave the totalTest as a dependency to useEffect it works but goes to an infinite loop how should i do this? can anyone help me please?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|