You shouldn't initialize a state variable for your initial object, you could just use the interface and declare it that way:
const initialList: ListInterface = {
listName: "List1",
list: ["One", "Two", "Three", "Four", "Five", "Six"]
};
Since you only want to update the list inside the object, you can use functional setState()
like this:
const handleSubmit = (event: any) => {
console.log("Submitted: " + text);
event.preventDefault();
setSelectedList((prevState) => {
return { ...prevState, list: prevState.list = [...prevState.list, text] };
});
};
When mapping
, make sure you pas a valid key
:
{selectedList.list.map((item, i) => {
return <h3 key={i}>{item}</h3>;
})}
Full code & updated sandbox:
import { useState } from "react";
import "./styles.css";
export default function App() {
interface ListInterface {
listName: string;
list: string[];
}
const initialList: ListInterface = {
listName: "List1",
list: ["One", "Two", "Three", "Four", "Five", "Six"]
};
const [selectedList, setSelectedList] = useState<ListInterface>(initialList);
const [text, setText] = useState("");
const handleChange = (event: any) => {
setText(event.target.value);
};
const handleSubmit = (event: any) => {
console.log("Submitted: " + text);
event.preventDefault();
setSelectedList((prevState) => {
return { ...prevState, list: prevState.list = [...prevState.list, text] };
});
};
return (
<div className="App">
{selectedList.list.map((item, i) => {
return <h3 key={i}>{item}</h3>;
})}
<form onSubmit={handleSubmit}>
<label>
Add To List:
<input type="text" value={text} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}