I am trying to post an array of objects. They show up in my HTML but when I console.log it always gives me an extra empty object. Which my backend doesn’t love.
Here’s the code on codesandbox:
https://codesandbox.io/embed/frosty-herschel-u8byqj?fontsize=14&hidenavigation=1&theme=dark
And here is the code:
const [animal, setAnimal] = useState('');
const [initialState, setInitialState] = useState<any>([])
const handleAdd = (text: any) => {
const newAnimal = {
id: uuidv4(),
animal: text
}
setInitialState([newAnimal, ...initialState]);
console.log(initialState)
}
return (
<div>
<FormControl fullWidth>
<InputLabel id="demo-simple-select-label">Animal</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={animal}
label="Animal"
onChange={(e: any) => setAnimal(e.target.value)}
name='worksFrom'
>
<MenuItem value='cow'>Cow</MenuItem>
<MenuItem value='pig'>Pig</MenuItem>
<MenuItem value='horse'>Horse</MenuItem>
</Select>
<Button disabled={!animal} onClick={() => handleAdd(animal)}>Add</Button>
</FormControl>
{
initialState.map((x: any) => {
return (
<div key={x.id}>{x.animal}</div>
)
})
}
</div>
)
}
I have tried a lot of different things but nothing seems to work
2
Answers
first, you should remove the object you are adding initially at:
and then, perhapes you don’t want to send empty animals, so you should add a if clause at your handleAdd to handle this situation:
this should help you. good luck with your studies;
You’re always initializing the array with an empty animal, because the animal state is always initialized as an empty text. Initialize the array to be empty and add some logic to enable adding animals only if the option was selected.
And to avoid adding an empty animal you could disable the button if the animal state is falsey.
That should disable the button unless you pick an animal from the select component.