Reputation: 59
How do I fix this 'Too many re-renders' error ?
I'm using try, catch method, useState, setState react hooks.
I'm trying to get data from api and print on web.
Error occurs here : setEmoticonThm(newEmoticonThms)
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
const [emoticonThm, setEmoticonThm] = useState([]);
const getToken = async () => {
try {
const emoticon = await axios.get(`${process.env.EMOTICON_ENDPOINT}`, {
headers: {
Authorization: accessToken
}
})
let newEmoticonThms = []
emoticon.data.emoticonPacks.map( (emoticon) => {
newEmoticonThms.push({
id: emoticon.id,
image:url + emoticon.image
})
})
setEmoticonThm(newEmoticonThms)
} catch (err) {
console.log(err)
}
}
const onClickSticker = () => {
getToken()
handleKeyboardOpen()
}
return (
...
<Sticker onClick={onClickSticker}/>
<TabContainer>
{emoticonThm.map((emoticon, index) => {
return (
<EmoticonThmButton
key={index}
onClick={setSelectedThm(index)}
>
<EmoticonThmImage
key={index}
onClick={onEmoticonClick}
src={img}
/>
</EmoticonThmButton>
)
})}
</TabContainer>
)
I added my code.
How can I get it right? TT
Upvotes: 0
Views: 614
Reputation: 1009
Instead of onClick={setSelectedThm(index)}
do onClick = {()=>setSelectedThm(index)}
onClick={setSelectedThm(index)}
is causing too many rerenders, as the function immediately gets called on the rendering phase. Instead of directly calling the function, you should pass the closure that wraps the function to delay its execution.
Upvotes: 3