I want to update setTopic without overriding previous state. But I am getting topic is not iterable error.
What I tried? I tried looking a different examples on stack overflow, But still couldn't figure out how to append updated state without losing previous state.
Also, which is a better way to save multiple topics : an array of objects, simply objects or simply array?
const AddTopic = (props) => {
const { subjectName } = props;
const [topic, setTopic] = useState([
{
topics: [
{
id: Math.random().toString(36).substr(2, 7),
topicName: "topic name",
subject: subjectName,
},
],
},
]);
const addTopicHandler = () => {
setTopic(
[...topic].map((item) => {
return {
...item,
id: Math.random().toString(36).substr(2, 7),
topicName: "another topic name",
subject: subjectName,
};
})
);
};
console.log(topic);