1

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 ?

2
  • 2
    Your find callback 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 use some() instead const hasParentId = data.some(({parentId}) => question.id === parentId); Commented Mar 24, 2022 at 20:40
  • Yes , you are right , thanks it's working now. Thanks @pilchard Commented Mar 24, 2022 at 20:42

2 Answers 2

1

You can check if any of the elements in the data have a matching ID using Array.some and if not then you can use concat or just the spread operator to add the new object to the existing data.

function arrayHandler(question) {
  if (!data.some((d) => question.id === d.parentId)) {
    setData((data) => [...data, { parentId: question.id, userChoice: "NO", child: [] }]);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think that now it shold work

function arrayHandler(question) {
const hasParentId = data.find((object) => question.id === object.parentId)
// concat if array do not have any question with same id. 
if (!hasParentId) {
  setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.