Search code examples
reactjsquery-stringreactivesearch

userQuery is undefined in <Route />


I'm just about done building my search UI with ReactiveSearch and just need to figure out how to display the results on '/results' with React Router 4 and npm package query-string.

I made a codesandbox here

My question is why is the userQuery undefined? I thought I followed this correctly?

Basically my search-layout.js is like this:

import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import querystring from 'query-string';

import Results from '../components/search/Results';

class SearchLayout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
  }

  componentDidMount(value) {
    this.setState({ value: this.state.value });
    console.log('This is the value: ', value);
    const userQuery = querystring.parse(this.props.location.search);
    // this.setState({ userQuery: this.state.userQuery });
    console.log('This is from query-string: ', userQuery);
  }

  render() {
    const { value } = this.state;
    console.log('This is value: ', value);
    const { userQuery } = this.state; // query string
    console.log('This is the userQuery: ', userQuery);
    const { match } = this.props; // path
    console.log('This is match props: ', match);

    return (
      <div>
        <Route path={`${match.path}?q=${userQuery}`} component={Results} />
        {this.state.value}
        {match.path}
        <br />
        {match.url}
        <br />
        {/* <Results /> */}
      </div>
    );
  }
}

export default SearchLayout;

The Results component that <Route /> is rendering contains the ReactiveList component. I know <Results /> works and displays the information because I originally just had React render it - just to make sure it worked. Now I'm trying to integrate RR4 and the query-string package and not sure where I'm going wrong.

If I replace path={${match.path}?q="${userQuery}"} with path="/results" - results display, but not based on the user query, its just default ReactiveList behavior.


Solution

  • Ok first lets see what you pass to query-string and what query-string want, for example we pass enter aaa in text box you pass ?q="aaa" but query-string want ?q=aaa

    so lets remove "" around over query stirng :

     const fixedQuery = this.props.location.search.replace(/['"]+/g, "");
     console.log(fixedQuery );
     const userQuery = querystring.parse(fixedQuery );
     console.log(JSON.stringify(userQuery));
     console.log(JSON.stringify(userQuery.q));
    

    please check this Sandbox