1

the search engine does not work, namely: going into devtools and the network tab when I type e.g. cow I have http: // api / Routes / Search? word = co when I add spaces I have: http: // api / Routes / Search? word = cow and searches and when I delete everything, I get: http: // api / Routes / Search? word = c and eg I will add spaces then display all results as it should strange...

<input   type="text" placeholder="search.." value={this.state.search} onChange={this.searchingRoute}     />
searchingRoute = (e) => {
        this.setState({
            search: e.target.value
        })
        if (this.state.search.length === 0) {
            fetch(`http://api/Routes`, {
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + sessionStorage.getItem("access_token")
                }
            })
                .then(response => {
                    if (response.ok) {
                        return response;
                    }
                    throw Error(response.status)
                })
                .then(response => response.json())
                .then(data =>
                    this.setState({
                        route: [...data],

                    })
                )
                .catch(error => console.log(error))
        }
        fetch(`http://api/Routes/Search?word=${this.state.search}`, {
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + sessionStorage.getItem("access_token")
            }
        })
            .then(response => {
                if (response.ok) {
                    return response;
                }
                throw Error(response.status)
            })
            .then(response => response.json())
            .then(data =>
                this.setState({
                    route: [...data],

                })
            )
            .catch(error => console.log(error))

    }
wika434
  • 41
  • 5

1 Answers1

0

The setState is asynchronous code, that is why in your searchingRoute function in the first if statement, it returns an older version of the search.

There's 2 ways to handle this: first method:

searchingRoute = (e) => {
  if (e.target.value.length === 0) {
    ...
  }
}

second method:

searchingRoute = (e) => {
  this.setState({ search: e.target.value });
};

componentDidUpdate(prevProps, prevState) {
  if (this.state.search !== prevState.search) {
    this.handleSearch();
  }
};

handleSearch = () => {
  const { search } = this.state;
  // handling search code...
}

Also, I recommend adding a debounce method to your search as you don't want the search to query your server every letter pressed but after the user has stopped pressing a letter for about 1 second or 500 milliseconds. You can learn more about this here: Perform debounce in React.js

kyapwc
  • 322
  • 2
  • 4
  • 9