Home > Back-end >  How to stop adding duplicate data to Array in react.js
How to stop adding duplicate data to Array in react.js

Time:03-25

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 ?

CodePudding user response:

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: [] }]);
  }
}

CodePudding user response:

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: [] }))
}

}

  • Related