Trying to create search function (React)


#1

I currently have a page of athletes / students for which a coach can sort through them using a search. However, when using the search right now I’m getting undefined for my reactive variable. Currently, I’m creating those variables inside my container, the following is a piece of my container (searchQuery and searching are being returned):

  export default createContainer(() => {

  let searchQuery = new ReactiveVar();
  let searching = new ReactiveVar(false);

  //const handle = Meteor.subscribe("students");
  console.log(searchQuery)

  const handle = Meteor.subscribe( 'students', searchQuery.get(), () => {
      setTimeout( () => {
        searching.set( false );
      }, 300 );
    });

Here is the publication:

Meteor.publish("students", function(search) {

  let query = {},
  projection = {limit: 10, sort: {firstname: 1}};
  
  if(search){
    let regex = new RegExp(search, 'i');

    query = {
      $or: [
        {firstname: regex},
        {lastname: regex}
      ]
    };

    projection.limit = 100;
  }

  return StudentDataCoach.find(query, projection);

Finally, here is the search component:

export default class Search extends React.Component{

  search(e){
    let value = this.refs.search.value;
    if(value !== '' && e.keyCode === 13){
      this.props.searchQuery.set(value);
      this.props.searching.set(true);
    }

    if(value === ''){
      this.props.searchQuery.set(value);
    }
  }

  render(){
    return(
      <div>
        <input type="text" name="search" placeholder="Find a student.." onKeyUp={this.search.bind(this)} ref="search"/>
      </div>
    );
  }
}

Here is the repo: GitHub Repo


#2

bumping up as I would like to know how this works too.


#3

Take a look at his linked to github repo - the issue was likely caused by defining his ReactiveVar’s within the createContainer function, which means that every time createContainer ran his ReactiveVar’s were clobbered/reset. His source repo now has them properly defined outside of createContainer, in his manageStudents container.


#4

hwilson is correct. I was able to fix the issue by moving the reactive variables outside the createContainer function.