The user has the possibility to enter his name. I get the name in a array. Example: ["Dilan", "Chris", "Robert"]
So what I'm trying to do is to get the name from the user, but also another value inside the array. Example:
initialName = {
name: "",
active: "",
};
Also, I need the initalName
to be inside an array.
This is what I have tried by far
const initialName = {
name: "",
active: ""
};
export default function AddingNames() {
const [names, setNames] = useState([initialName ]);
const handleAddClick = () => {
setLanguages([...names, initialName]);
};
const handleItemChanged = (event, index) => {
const value = event.target.value;
const list = [...initialName];
list[index] = value;
setNames(list);
console.log(names);
};
And this error is showed: TypeError initialName is not iterable
What I want to get from the user its just the name value in the initialName. How can I make it work?
CodePudding user response:
So initial name is not iterable here as you are trying to do in usestate([]) because initial name is an object not an array. If you had an array say:
let users = [{ name: "", active: "", }]
Then you could iterate over the users array and access the name of a user by
let variable = user[0].name
CodePudding user response:
you can only use ...
in case of iterable variable, in this case initialName is not iterable since its object
I suppose you are trying to achieve array that looks something like this:
list =
[
{name: "boo", active: "foo"},
{name: "john", active: "doe"}
]
In this case what you could do is
list[index] = {name: value, active: ""};
setNames(list)