I'm saving data in this state but I would like to send "matches" to the server only if a variable is true, how can I do it?
Thanks in advance!
const [formData, setFormData] = useState({
user_id: cookies.UserId,
first_name: "",
dob_day: "",
dob_month: "",
dob_year: "",
show_gender: false,
gender_identity: "man",
gender_interest: "woman",
url: "",
about: "",
matches: [] // send only if variable is true
})
CodePudding user response:
You can write the sending part inside a useeffect.
useEffect(
() => {
yourVariable && sendingFucntion();
},
[yourVariable]
)
CodePudding user response:
Remove matches
from your default state declaration, then, in your condition try something like this :
if(true /** your condition */) {
setFormData({
...formData, /** current data*/
matches:[] /** add your key matches with correct array value.*/
})
}
I guess probably something like this ? :
if(matchsArray && Array.isArray(matchsArray) && matchsArray.length > 0) {
setFormData({
...formData, /** current data*/
matches:matchsArray /** add your key matches with correct array value.*/
})
}
Don't forget to put your data state in a real FormData to build your POST request after. Like :
const finalFormData = new FormData()
finalFormData.append(
'data', /** your key catch by your backend api*/
formData /** the react state*/
)
Let me know if it's help you. :)