Search code examples
react-nativeoperators

React Native can not using Spread Operator to update object in array


i have the state that control the flatList data

const [data, setData] = useState([])

i have a object like below(after get from network, it's show success in FlatList)

data = [{
  'name' : 1,
 },
 {'name' : 2,
 }]

Now i want to update first object {'name': 1} by add some key/value like this:

{ 'name' : 1, 'text' : 'this is text'}

Here is my code:


const mathched = data[0]
mathched = [
              ...mathched,
              {'text': 'this is text'}
            ]

But i got error: TypeError: "mathched" is read-only

I tried other solution by set new key to object:

const newData = [...data]
const mathched = newData[0]
mathched['text'] = 'this is text'
setData(newData)

But data not changed

Can someone guide me how to use Speard Operator to done my solution? Thanks


Solution

  • The problem is that the state value is a read-only variable that can be modified only via the setter, setData in this case.

    When you do const matched = data[0] then matched = newData[0] you are attempting to store the new value without the setter usage.

    One way to go would be:

    // Usign for example Lodash clone
    const newClonedData = clone(data);
    newClonedData[0] = { ...matched[0], {'text': 'this is text'} };
    setData[newClonedData];