Home > Enterprise >  How to set a property of an array of objects state in useState?
How to set a property of an array of objects state in useState?

Time:08-19

I have a useState like this:

  const [sortItems, setSortItems] = useState<sortedItem[]>(items);

And an interface sortedItem:

interface sortedItem {
  label: string; 
  sortingType: string;
  key: string;
}

items are:

[{key: 'name', label: 'Name', sortingType: 'initial'},
{key: 'name1', label: 'Name1', sortingType: 'initial'}]

I tried to change sortingType value of the first object in the array(as a simple example):

setSortItems({ ...sortItems, sortItems[0].sortingType:'another_value' });

but it is producing an error

CodePudding user response:

You are trying to set an Object to an Array. You can check out react documentation to learn how to update an array state in the right way

Here my example code:

const newSortItems = sortItems.map((item, index) => {
  if (index === 0) {
    return {
      ...item,
      sortingType: 'another_value',
    };
  } else {
    return item;
  }
});
setSortItems(newSortItems);

Solution without using map :

const newSortItems = [...sortItems];
newSortItems.find((item, index) => index === 0 ).sortingType = 'another_value';
setSortItems(newSortItems);

Another solution, look simpler:

const newSortItems = [
  {
    ...sortItems[0],
    sortingType : 'another_value'
  },
  ...sortItems.filter((item, index) => index !== 0)
]
setSortItems(newSortItems);

CodePudding user response:

You can do it like this .

Create a variable to hold the new sorted array ,save the sorted array in the variable

const newArray=sortItems.map((item,index)=>{
if(index != 0)return item;
return item.sortingType="another_value";
});

set this sorted array to the state

setSortItems(newArray);

CodePudding user response:

You could use the slice method.

setSortItems((state) => [
  {...state[0], sortingType: "value"},
  ...state.slice(1)
]);

PS: Note how I've used the state from the setState callback. This helps you avoid stale closures.

  • Related