I followed the approach as the answer in this question suggested The issue is that I want to construct an Array using setState and I dont; want to add duplicate data.
here is the sample data
const data = [
{
parentId: '1',
userChoice: 'NO',
child: []
},
{
parentId: '2',
userChoice: 'NO',
child: []
},
}
I'm catching the parentId from question.id from user input. If there is the same question then I don't want to concat into the array.
This is how I'm trying.
const [data, setData] = useState([]) // state
function arrayHandler(question) {
const hasParentId = data.find((parentId) => question.id === parentId)
// concat if array do not have any question with same id.
if (!hasParentId) {
setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
}
}
But this is not working, How can I fix this ?
findcallback is accessing the object incorrectly, perhaps you meant to desctructure?data.find(({parentId}) => question.id === parentId);also since you're using the result as a boolean you might usesome()insteadconst hasParentId = data.some(({parentId}) => question.id === parentId);