user6863891
user6863891

Reputation:

React AutoSuggest: search text box not updating on suggestion selection

I am using the react autosuggest library to build auto-suggestion

import Autosuggest from "react-autosuggest";
import React, { Component } from "react";
import QueryString from "query-string";

class AutoSuggestSearch extends Component {
  constructor() {
    super();
    this.state = {
      value: "",
      suggestions: []
    };
    this.getSuggestionValue = this.getSuggestionValue.bind(this);
    this.renderSuggestion = this.renderSuggestion.bind(this);
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue
    });
  };

  getSuggestionValue = suggestion => suggestion.fullNameSuggestion;


  renderSuggestion = suggestion => <div>{suggestion.name}</div>;

  onSuggestionSelected = (event, { suggestion}) => {
    console.log(suggestion);
    this.setState({
      suggestions: [],
      value: suggestion.name
    });
  };

  onSuggestionsFetchRequested = ({ value }) => {
    const params = {
      stationPrefixName: value
    };
    const queryParams = QueryString.stringify(params);
    fetch(`http://localhost:8000/api/suggest?${queryParams}`)
      .then(res => res.json())
      .then(data => {
        console.log(data);
        this.setState({
          suggestions: data
        });
      })
      .catch(console.log);
  };

  // Autosuggest will call this function every time you need to clear suggestions.
  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: [],
      value: ""
    });
  };

  render() {
    const { value, suggestions } = this.state;

    const inputProps = {
      placeholder: "Search",
      value,
      onChange: this.onChange
    };


    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        onSuggestionSelected={this.onSuggestionSelected}
        getSuggestionValue={this.getSuggestionValue}
        renderSuggestion={this.renderSuggestion}
        inputProps={inputProps}
      />
    );
  }
}

export default AutoSuggestSearch;

The suggestion gets rendered on typing on search box as well as the logging inside onSuggestionSelected gets logged correctly but the input search box does not update correctly.

On debugging further I found that onSuggestionsClearRequested also gets invoked after onSuggestionSelected which is causing the search input box to be empty.

I validated this by adding const string inside onSuggestionsClearRequested

  onSuggestionsClearRequested = () => {
    alert("clear request");
    this.setState({
      suggestions: [],
      value: "mysearch"
    });
  };

Is there anyway to prevent onSuggestionsClearRequested invokation on suggestion selection? Or updating the search query value inside onSuggestionsClearRequested is the correct way?

Upvotes: 0

Views: 2137

Answers (3)

Vijit Nagar
Vijit Nagar

Reputation: 31

You can use componentDidUpdate or UseEffect if you are using it in functional component.

I have used react-autosuggest in functional component and clear suggestion works only if value doesn't matches with the suggestions:

const [clear, setClear] = useState(false);
const handleOnChange = newValue => {
  setValue(newValue);
  setClear(false);
};
useEffect(() => {
  if (!suggestions.some(option => option === value) && clear) {
    setValue('');
  }
}, [clear]);

const onSuggestionsClearRequested = () => {
  setClear(true);
  setSuggestions([]);
};

Upvotes: 1

raj m
raj m

Reputation: 2023

Hi you may approach with hooks. It looks good and less coding.

You may find below

https://github.com/rajmaravanthe/react-auto-suggestion

Upvotes: 0

shubham
shubham

Reputation: 449

The onSuggestionsClearRequested function gets called everytime you click outside the search input, which is the default implementation of the libary being used,

What we implement in onSuggestionsClearRequested is upto us. you can change the implementation as follows : Approach keep keyword inside input if available options are not selected

  onSuggestionsClearRequested = () => {};

this should provide the desired implementation behaviour.

Upvotes: 0

Related Questions