Dharmik soni
Dharmik soni

Reputation: 363

I am trying to push data into array defined in useState in react, but the data is not being pushed in to array

I am trying to push some data into array defined in useState, but the data is not getting pushed in the array.

//Below is the code

 const [formData, setFormData] = useState({
        name: "",
        technology: [],
        description: "",
        technoText: ''
    });

const { name, description, technoText, technology } = formData;
    const onChange = e => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

const onAdd = (e) => {
    e = e || window.event;
    const newElement = { id: uuid.v4(), value: technoText }
    if(e.keyCode === 13){
        setFormData({...formData, technology: currentArray => [...currentArray, newElement]});
        console.log(newElement);
        console.log('this is technology', technology)
    }
}

//The data for newElement is being logged in the console, but not getting pushed in the array technology.

Upvotes: 2

Views: 615

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

Set the technology key to an Array and not to a function or use a functional useState:

const [formData, setFormData] = useState({
  technology: []
});

const { name, description, technoText, technology } = formData;

const onChange = e => {
  setFormData({ ...formData, [e.target.name]: e.target.value });
};


const onAdd = e => {
  e = e || window.event;
  const newElement = { id: uuid.v4(), value: technoText };
  if (e.keyCode === 13) {

    setFormData({ ...formData, technology: [...technology, newElement] });

    // v You defined the `technology`'s value as a function
    // setFormData({...formData, technology: currentArray => [...currentArray, newElement]});

    // I think you ment using a functional useState like so:
    setFormData(prevState => ({
      ...formData,
      technology: [...prevState.technology, newElement]
    }));

    // Or more like
    setFormData(({ technology: currentArray }) => ({
      ...formData,
      technology: [...currentArray, newElement]
    }));
  }
};

Upvotes: 1

Related Questions