I have such array with fields id and title in object
const cols = [
{
id: 0,
title: "TODO"
}, {
id: 1,
title: "InProgress"
}, {
id: 2,
title: "Testing"
}, {
id: 3,
title: "Done"
},
]
I have a state: const [colArray, setColArray] = useState(cols);
And I need to find object in this array by id and put into this object new title value.
I tried this:
const EditColName = () => {
setColArray(prevState => [...prevState, colArray.filter(item => item.id === editColId){ title: newTitle}])
}
But i have an error
TS2345: Argument of type '(prevState: { id: number; title: string; }[]) => ({ id: number; title: string; } | { id: number; title: string; }[] | { title: string; })[]' is not assignable to parameter of type 'SetStateAction<{ id: number; title: string; }[]>'.
CodePudding user response:
You are using a spread operator on the previous state, but not the filtered array. So you are getting a type error because your data has an array of your 'cols' and then a nested array of the filtered results.
If you just want to set the colArray to the filter then don't use the previous state:
setColArray(colArray.filter(item => item.id === editColId))
Or if you do:
setColArray(prevState => [...prevState, ....colArray.filter(item => item.id === editColId), { title: newTitle}])
CodePudding user response:
Need to find object with matching id (use .find()) and pass into the array overriding value of title (use spread operator).
const EditColName = () => {
setColArray(prevState => [...prevState, { ... prevState.find(item => item.id === editColId)! , title: newTitle }])
}
.find() returns undefined in some cases (when no array item matches the property). So you have to use TS non null assertion operator (!) to let TS know that there will be definitely be a value this time.
