0

I would like to get the user's input value and then use it in my Redux's action fetchData. I think to change a variable in my component state when input.onChange, then get the string from it to call my method with the argument.

I got an error this is undefined pointed on handleChange.

import React, { Component } from 'react';
import { connect } from "react-redux";
import { fetchData } from "../actions/fetchData";

class SearchBar extends Component {

    constructor() {
        super()

        this.state = {
            tags: ''
        }
    }

    buttonClicked() {
        this.props.fetchData(this.state.tag)
    }

    handleChange(e) {
        this.setState({ tags: e.target.value })
    }

    render() {
        return (
            <section className="section">
                <div className="columns">
                    <div className="column is-half is-offset-one-quarter">
                        <div className="field has-addons">
                            <div className="control is-expanded">
                                <input className="input" type="text" placeholder="dog" onChange={this.handleChange}/>
                            </div>
                            <div className="control">
                                <a className="button is-info" onClick={this.buttonClicked}>
                                    Random!
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        )
    }
}

export default connect(null, { fetchData })(SearchBar);

What do I miss here ?

Ragnar
  • 2,550
  • 6
  • 36
  • 70

1 Answers1

2

You have to bind this to your functions, try this:

...
constructor() {
  super()

  this.state = {
      tags: ''
  }
  this.buttonClicked = this.buttonClicked.bind(this);
  this.handleChange = this.handleChange.bind(this);
}
...

Also, take a look at why do you need to bind this on the constructor.

Tiago Alves
  • 2,290
  • 13
  • 32
  • Ok I will try that. But this is the good approach also ? I just saw I can use arrow function to don't have to write this ugly piece of code ;) – Ragnar Feb 19 '18 at 17:41
  • It's not ugly, it's just the way we do it. But you are right, you can use arrow functions as well, but keep in mind that you might not want to bind `this` always, that's why binding in the constructor is handy. – Tiago Alves Feb 19 '18 at 17:48