I want to update an object state with a function updateDatas. I pass key, potentially subKey, and value as argument of this function.
interface Datas {
code: number;
item1: Item;
}
interface Item {
id: number;
name: string;
}
const [datas, setDatas] = useState({
code: 42,
item1: {
id: 1,
name: 'foo'
}
});
function updateDatas(key: string, subKey: string, value: any) {
if (subKey) {
setDatas({...datas, key: {...datas.key, subKey: value}});
} else {
setDatas({...datas, key: value});
}
}
updateDatas('code', 23);
updateDatas('item1', 'name', 'bar');
But it doesn't work, I have this Typescript error :
Argument of type '{ key: any; code: number; item1: Item; }' is not assignable to parameter of type 'SetStateAction'. Object literal may only specify known properties, and 'key' does not exist in type 'SetStateAction'.ts(2345)
setDatas({...datas, [key]: {...datas.key, [subKey]: value}});