'React SetState not updating in a function component
i'm working on a MERN project and it's been weeks that i have an issue with React states. I use a state to display a Popup or not.
That's the way i'm displaying it:
{OptionsPopUpState
? <OptionsPopUp func={OptionsPopUpfunc} name={OptionsPopUpData.name} id={OptionsPopUpData.id} shared={OptionsPopUpData.shared} languageQuestion={OptionsPopUpData.languageQuestion} languageAnswer={OptionsPopUpData.languageAnswer} />
: ""
}
The function passed in props is the one which hide or display it depending on the state.
Here's the function:
const OptionsPopUpfunc = (event)=>{
if(event){
event.nativeEvent.stopImmediatePropagation();
event.stopPropagation();
}
let clicked = event.target
let attributes = JSON.parse( clicked.getAttribute("data-info") ) //get data passed (id and name)
if(attributes){
SetOptionsPopUpData({"name":attributes.name, "id":attributes.id, "shared": attributes.shared, "languageQuestion": attributes.languageQuestion, "languageAnswer": attributes.languageAnswer}) //set data to pass in props for the popup
}
if(OptionsPopUpState){
SetOptionsPopUpState(false)
console.log("New state "+OptionsPopUpState)
refresh(); //refresh when close with delay
}
else{
console.log("display")
SetOptionsPopUpState(true);
}
}
I don't get why it is not working because i use exactly the same code for an other popup and it works perfectly. On the top of it, when i print the state just after having changed it, no change...
Edit: Refresh function
const refresh = ()=>{
fetch('/get_flashcards', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'token': cookies.token
})
}).then((response)=>{
if(response.ok){
response.json().then((data)=>{
var flashcard = data.successfull.map(flashcardSerie=>{
return(
<div class="relative w-80 py-3 bg-white-ctm mx-auto inset-x-0 rounded-md backdrop-blur-4xl p-2 flex flex-row" onClick={()=>{redirect(flashcardSerie._id)}}>
<h2 class="text-white font-medium pl-4 text-left">{flashcardSerie.name}</h2>
<img onClick={OptionsPopUpfunc} data-info={JSON.stringify({'name':flashcardSerie.name,'id':flashcardSerie._id, 'shared':true, 'languageQuestion':flashcardSerie.languageQuestion, 'languageAnswer':flashcardSerie.languageAnswer}) } class="absolute right-4 w-6 h-6" src={IconMore}/>
</div>)
})
SetFlashCards(flashcard)
SetInit(true)
})
}else if(response.status === 403){
document.location = "login"
}
})
}
Does anyone understand the problem's origin ? Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
