1

I'm trying to make a SearchResults component which shows search results based on what's in the query string, which is updated by a SearchForm component. It has been recommended here that I use history.listen. Great idea, except for some reason when called in componentWillMount, history.listen is not being triggered:

componentWillMount() {
    let location;
    this.props.history.listen(routerState => {
        console.log('current location:' + routerState); //never logs anything...
        location = routerState;
    });
    console.log(location); //'undefined'
    let search = location;
    console.log(search); //'undefined'
    this.setState({ search: search.search }); //throws "Cannot read property search of undefined error
}

This seems strange, since I use history.listen here pretty much exactly as the previous poster did in that link. I have also tried putting this logic in componentDidMount with the same results.

My component is wrapped by withRouter here.

Toby Weed
  • 524
  • 5
  • 18

1 Answers1

2

Solved this by implementing logic inside the listen call, as well as putting initialization logic inside of componentDidMount--this is necessary because history.listen is only triggered on change, not on the initial render.

My code:

componentWillMount() {
    this.unlisten = this.props.history.listen(location => {
        console.log('current location:' + location);
        let query = qs.parse(location.search);
        console.log(query) //logs an object with attributes based on the current query string
    });
}

componentWillUnmount() {
    this.unlisten();
}

componentDidMount() {
    let query = qs.parse(this.props.location.search);
    console.log(query); //logs an object with attributes based on the current query string
}
Toby Weed
  • 524
  • 5
  • 18