Optimize search result by sending few/less requests to backend from React UI

Viewed 20

I am sending request to backend on users input in Input Field, I have already implemented debouncing even though, my UI is lagging little bit, what can I do/implement along with debouncing to improve search results.

Actually backend search is very heavy call, are there any other ways/tricks/techniques which I can use to improve it further

[My backend is taking about 1500ms to 4000ms to process request as number of records are more than 100000]

1 Answers

Using axios cancelToken feature was very helpful, if the response of the first request arrives after the response of the second request, then we might render inconsistent data.

import axios from "axios"
import React from "react"
import "./App.css"

function App() {
  let cancelToken
  const handleSearchChange = async e => {
    const searchTerm = e.target.value

    //Check if there are any previous pending requests
    if (typeof cancelToken != typeof undefined) {
      cancelToken.cancel("Operation canceled due to new request.")
    }

    //Save the cancel token for the current request
    cancelToken = axios.CancelToken.source()

    try {
      const results = await axios.get(
        `http://localhost:4000/animals?q=${searchTerm}`,
        { cancelToken: cancelToken.token } //Pass the cancel token to the current request
      )
      console.log("Results for " + searchTerm + ": ", results.data)
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <div style={{ marginTop: "3em", textAlign: "center" }}>
      <input
        style={{ width: "60%", height: "1.5rem" }}
        type="text"
        placeholder="Search"
        onChange={handleSearchChange}
      />
    </div>
  )
}

export default App
Related