Laylaz
Laylaz

Reputation: 37

(TypeError): Cannot read property 'props' of undefined

I have a component with the name Search that is responsible for any searching

code:

class Search extends Component {
  state = {
    searchResult: []
  }

  async componentDidMount() {
    await this.props.searchAssets(this.props.match.params.name);
    this.handleState();
  }

  handleState() {
    this.setState({ searchResult: this.props.searchResult });
  }

  async handleSearch(e) {
    e.preventDefault();
    await this.props.searchAssets(e.target.q.value);
    this.handleState()
  }

  render() {
    return (
      <div className="content-block">
        <form onSubmit={this.handleSearch} className="search-form">
            <button>بحـث</button>
            <input type="text" defaultValue={this.props.match.params.name} name="q" placeholder="Est: Game of thrones, Vikings or Deadpool" />
        </form>
        <div className="display-latest">
          ***the div where search results are shown***
        </div>
      </div>
    )
  }
}

and it worked perfectly fine until I tried to add another search form on the page, I attempted to try making it reuse the action from coming from redux but it kept giving me this error

(TypeError): Cannot read property 'props' of undefined

even when I tried to use a constructor and bind it.

also if there's a better way to fire a search without loading the page I'd be happy to take notes. :)

Upvotes: 0

Views: 577

Answers (1)

Pranay Tripathi
Pranay Tripathi

Reputation: 1882

The function handleState and handleSearch are missing reference to the this. You can have the reference in following two ways:

  1. If you are using transform-class-properties which seems like your case, you can change the functions to arrow functions.
  2. You have to bind the function in the constructor using following way:

    this.handleState = this.handleState.bind(this);

Either of these should fix the issue here.

Upvotes: 2

Related Questions