Search code examples
reactjsarraysobjectpoststate

Posting array of objects in React is giving me an extra object


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


Solution

  • first, you should remove the object you are adding initially at:

    const [initialState, setInitialState] = useState([]);
    

    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:

    const handleAdd = (text) => {
        if (text.length === 0) {
          return;
        }
        const newAnimal = {
          id: uuidv4(),
          animal: text
        };
        setInitialState([newAnimal, ...initialState]);
      };
    

    this should help you. good luck with your studies;