1

I am newbie in Reactjs. I am making a form in which form data will store in an array and shows on same page after submission. I am using push() to store data in array but when I press submit button then error encountered:

Cannot read property 'push' of undefined

I am unable to store data in array. and Here is my code snippet:

import React from "react";
data = [{ firstName :'', lastName:'', username:'' }];

export default class Form extends React.Component {

  state = {
    firstName: "",
    lastName: "",
    username: ""
  }

  change = e => {
    this.props.onChange({ [e.target.name]: e.target.value });
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  onSubmit = e => {
    e.preventDefault();
    console.log(this.state);

    let firstName = this.state.firstName.value;
    let lastName = this.state.lastName.value;
    let username = this.state.username.value; 


    this.setState({
      data :  this.state.data.push({firstName, lastName, username})
    })


  render() {
    return (
      <form>
        //Form Fields
     )
    }

I want help regarding this. Thanks a lot!!!

Vishal Donga
  • 13
  • 1
  • 4
  • Firstly, set the initial state in the constructor. Secondly, NEVER mutate the state. `push()` mutates the array you call it on. Make a copy of the state array then mutate that. Thirdly, in your `setState()` call, you're setting `data` equal to the _return_ value of the push call, which is the array's new length, not the new array itself. – Jayce444 Jul 12 '18 at 07:45

7 Answers7

1

its better when you use setState like there:

import React from "react";
    data = [{ firstName :'', lastName:'', username:'' }];

    export default class Form extends React.Component {

      state = {
        firstName: "",
        lastName: "",
        username: "",
        data
      }

      change = e => {
        this.props.onChange({ [e.target.name]: e.target.value });
        this.setState({
          [e.target.name]: e.target.value
        });
      };

      onSubmit = e => {
        e.preventDefault();
        console.log(this.state);

        let firstName = this.state.firstName.value;
        let lastName = this.state.lastName.value;
        let username = this.state.username.value; 

        /**
         * change here!!
         */
        this.setState(prevState => ({
            ...prevState,
            data: [...prevState.data,{ firstName, lastName, username }]
         }))
       }

      render() {
        return (
          <form>
            //Form Fields
         )
        }

more info: https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

dvvtms
  • 627
  • 3
  • 10
  • I got this error after changing this: Cannot convert undefined or null to object at this line: data: [...prevState.data,{ firstName, lastName, username }] – Vishal Donga Jul 12 '18 at 08:16
  • @VishalDonga yep, its not initialized state with default `data`. see edited answer – dvvtms Jul 12 '18 at 08:21
0

You need to initialise the data as an array in state.

state = {
  data = []
}
Ryan C
  • 426
  • 2
  • 6
0

Just took a cursory look, I think you should move some code around. Your data definition should be moved to the class and you can quiet possibly use it to initialize your state. As others have suggested, you state initialization should be in the constructor. Try this:

    import React from "react";


    export default class Form extends React.Component {
    constructor() {
      state = {
       data : [{ firstName :'', lastName:'', username:'' }]
      }
    }

      change = e => {
        this.props.onChange({ [e.target.name]: e.target.value });
        this.setState({
          [e.target.name]: e.target.value
        });
      };

      onSubmit = e => {
        e.preventDefault();
        console.log(this.state);

        let firstName = this.state.firstName.value;
        let lastName = this.state.lastName.value;
        let username = this.state.username.value; 


        this.setState({
          data :  this.state.data.push({firstName, lastName, username})
        })


      render() {
        return (
          <form>
            //Form Fields
         )
        }
ArrowHead
  • 609
  • 5
  • 16
0

Inside setState you can not use push() method. So instead of pushing inside setState just first push outside and then set it inside setState

data.push({firstName,lastName,username}); this.setState({ data:data, })

0

First of all - and this is super important - never modify state directly! Check out this link of the documentation.

Next the reason you are getting your error, is because state does not know about your data array.

If you want to do stuff correctly, you should use an updater function to modify your state.

J. Hesters
  • 13,117
  • 31
  • 133
  • 249
0

try with

this.setState({ data: [...this.state.data, {firstName, lastName, username}] });

TranDuc
  • 23
  • 1
  • 10
0

Got the answer after applying this solution in onSubmit() function:

 onSubmit = e => {
    e.preventDefault();
    console.log(this.state);

     data =
     {
        firstName : this.state.firstName,
        lastName : this.state.lastName,
        username : this.state.username, 
        email : this.state.email,
        password : this.state.password,
        birthDay : this.state.birthDay,
        birthMonth : this.state.birthMonth,
        birthYear : this.state.birthYear,
        gender : this.state.gender
    }
     this.state.data.push(data)
     this.setState(this.state);



   };
Vishal Donga
  • 13
  • 1
  • 4