Jorge Merino
Jorge Merino

Reputation: 123

What am i doing wrong? TypeError: this is undefined

I'm creating simple form with a React component to send via axios.post, so I'm trying to capture the input data but for some reason I get a

this is undefined

when trying to change the state.

I wrote name: 'hello', to just change the state to something an visualize in the form if it is working. Same as 'TryDescription'.

export default class Posts extends Component {
    constructor(props){
        super(props);
        this.state = {
            error: null ,
            posts: [],
            isLoaded: false,
            name : null,
            description: null,
        }
    }
    static handleSubmit(event){
        event.preventDefault();
        console.log('hello');
    };
   handleInputchange(event){
       console.log(event.target.value);
      this.setState({
          error : null ,
          posts: [] ,
          isLoaded:false,
          name:'Hello',
          description: 'TryDescription',
      })


   };

    render() {
        const { error, isLoaded, posts , name , description } = this.state;
    return (

        <div className="container">
            <form onSubmit={Posts.handleSubmit}>
                <div className="form-row">
                    <div className="form-group col-md-6">
                        <label htmlFor="name">Name</label>
                        <p>The name is:{name}  </p>
                        <input onChange={this.handleInputchange} type="text" name='name' className="form-control" id="name" placeholder="Tittle"/>
                    </div>
                    <div className="form-group col-md-6">
                        <label htmlFor="description">Description</label>
                        <p>The description is:{description}  </p>
                        <input onChange={this.handleInputchange}  name="description" type="text" className="form-control" id="description" placeholder="Description"/>
                    </div>
                </div>

                <button type="submit" className="btn btn-primary">Create</button>
            </form>

            <div className="row">
                {posts.map((post) =>
                    <div className="col-3" key={post.id} >
                    <div className="card"  style={{width: 18 + 'rem'}}>
                        <div className="card-body">
                            <h5 className="card-title">{post.name}</h5>
                            <h6 className="card-subtitle mb-2 text-muted">Subtítulo</h6>
                            <p className="card-text">{post.description}</p>
                            <a href="#" className="card-link">Card link</a>
                            <a href="#" className="card-link">Another link</a>
                        </div>
                    </div>
                    </div>
                )}
            </div>

        </div>


    )
}

I would expect that doing:

this.setState({
          error : null ,
          posts: [] ,
          isLoaded:false,
          name:'Hello',
          description: 'TryDescription',
      })

name takes the 'Hello' string value but nothing.

Upvotes: 0

Views: 688

Answers (4)

Gautam Patadiya
Gautam Patadiya

Reputation: 1411

You can use the arrow function here. that will help you to fix the error. something like this:

   handleInputchange = (event) => {
        // write logic
   }

Good Luck.

Upvotes: 0

Dinith Tharushka
Dinith Tharushka

Reputation: 1

Binding the State would fix the issue. Remember, you have to do the binding inside the constructor. The modification can be done with '.bind(this)' as below.

 this.handleInputchange = this.handleInputchange.bind(this);

And finally your constructor should look like this:

  constructor(props){
    super(props);
    this.state = {
        error: null ,
        posts: [],
        isLoaded: false,
        name : null,
        description: null,
    }

    this.handleInputchange = this.handleInputchange.bind(this);
}

Upvotes: 0

ravibagul91
ravibagul91

Reputation: 20755

You need to bind this to your handleInputchange function,

this.handleInputchange = this.handleInputchange.bind(this); //Add this in your constructor

Another issue with your code is,

<form onSubmit={Posts.handleSubmit}>

Don't write such event, you just need to do this,

<form onSubmit={this.handleSubmit}>

And your handleSubmit function should be only this,

handleSubmit(event){
    event.preventDefault();
    console.log('hello');
};

Again you need to bind this to handleSubmit function,

this.handleSubmit = this.handleSubmit.bind(this); //Add this in your constructor

Or, another way is declare your functions using arrow function notation,

handleSubmit = (event) => {
   event.preventDefault();
   console.log('hello');
};


handleInputchange = (event) => {
  console.log(event.target.value);
  this.setState({
     error : null ,
     posts: [] ,
     isLoaded:false,
     name:'Hello',
     description: 'TryDescription',
  })
};

In this case you don't need to bind this to your function's.

Upvotes: 1

Ryan Nghiem
Ryan Nghiem

Reputation: 2438

You should bind handleInputchange function in contructor

constructor(props){
    super(props);
    this.state = {
        error: null ,
        posts: [],
        isLoaded: false,
        name : null,
        description: null,
    }
    this.handleInputchange = this.handleInputchange.bind(this)
}

Upvotes: 0

Related Questions