0

I have an array of objects with the below structure, how can I update the object's data (file) based on one of the object property (name)? for example how can I update the object named: test1 with a new file object?

I have tried that but the correct object isn't being updated, a new object is being pushed to the array instead, what am I doing wrong?

const [files, setFiles] = useState(fileArr)

const setFile = (name, data) => {
  setFiles(files => ({...files, [name]: {...files[name], ...data}}))
}

fileArr array:

const fileArr= [
  {
    name: 'test1',
    status: 'Required',
    file: {}
  },
  {
    name: 'test2',
    status: 'Required',
    file: {}
  },
  {
    name: 'test3',
    status: 'Required',
    file: {}
  }
]
user3378165
  • 6,546
  • 17
  • 62
  • 101

1 Answers1

3

Assuming the following structure

const fileArr= [
  {
    name: 'test1',
    status: 'Required',
    file: {}
  },
  {
    name: 'test2',
    status: 'Required',
    file: {}
  },
  {
    name: 'test3',
    status: 'Required',
    file: {}
  }
]

The correct way of updating an object based on name to replace file is

const onChange = (name, data) =>{
    setItems(items => items.map(item =>{
        if(item.name === name)
            //assuming you want to spread instead of overwrite 'file'
            return {...item, file:{...item.file, ...data}}

        return item
    }))
}

Also you're initializing your state with fileList which based on how you're trying to update is an object, but you posted fileArr as your data structure. So I'm assuming that you want to perform your operations in fileArr instead of fileList (which I don't know how it's look like)

Dupocas
  • 20,285
  • 6
  • 38
  • 56