Push() is not working in react

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!!!

7 answers

  • answered 2018-07-12 07:41 Ryan C

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

    state = {
      data = []
    }
    

  • answered 2018-07-12 07:42 dbvt10

    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

  • answered 2018-07-12 07:42 ArrowHead

    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
             )
            }
    

  • answered 2018-07-12 07:43 Mukesh Burnwal Mike

    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, })

  • answered 2018-07-12 07:47 J. Hesters

    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.

  • answered 2018-07-12 07:55 TranDuc

    try with

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

  • answered 2018-07-12 09:00 Vishal Donga

    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);
    
    
    
       };