skip to Main Content

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


  1. 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;

    Login or Signup to reply.
  2. 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.

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

    And to avoid adding an empty animal you could disable the button if the animal state is falsey.

    <Button disabled={!animal} onClick={handleSubmit}>Add</Button>
    

    That should disable the button unless you pick an animal from the select component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search