The following code works, i.e. updates the object state variable successfully:
import { useState } from 'react'
import './App.css';
function App() {
const [config, setConfig] = useState({
status: "online",
maxFiles: 99
});
const addConfigEntry = () => {
setConfig(n => {
const n2 = { ...n };
n2.errors = 0;
return n2;
})
};
return (
<div className="App">
<button onClick={addConfigEntry}>Add a Entry</button>
<ul>
{Object.entries(config).map((entry, index) => {
return (
<li key={index}>{entry[0]} = {entry[1]}</li>
)
})}
</ul>
</div>
);
}
export default App;
But I'm getting this warning from TypeScript which makes me think that this is not the optimal way to update an object variable:
Is there a more correct, React-compliant way to update an object variable?
Addendum
Note that this does not work (response to a comment):
setConfig({ ...config, errors: 0 }); // will not be added!
setConfig({ ...config, errors2: 0 });