简体   繁体   中英

How to implement autocomplete user search in React and Django Rest Framework

So basically I'd like to implement a user search system in react which would send an api request to my django backend which would send back the results. This is an easy implementation if I wanted the results once I hit search but I want the results displayed as autocompletes. For example in Twitter it autocompletes what you are searching for. How would I implement this. I am using axios for my requests if that helps. A side note would be that I'd like to wait maybe a second or 2 before sending the request because I would want to send to many requests and slow down the server. Thank you!

Recipe: any HTTP client(with/without cancellable HTTP client), denounce function(lodash has good one), CSS design the suits displaying your results in.

Here is the basic idea You create a denounced function and get an instance of that function that can be cancelled, so every time the user hit the search bar we cancel the old subscriptions to that function and resubscribe with new denounced timeout, when that timeout ends we call the function to hit the API and get the response(which represent the autocomplete response) to be display as you like.

import React, { useState } from 'react';
import axios from 'axios';
import { debounce } from 'lodash';

let debouncedFunction: any;


function App() {

  const [inputValue, setInputValue] = useState('');

  const onSearchChange = (event: any) => {
    try {

      setInputValue(event.target.value);

      /**
       * cancel old saved debounced functions
       */
      if (debouncedFunction && debouncedFunction.cancel)
        debouncedFunction.cancel();

      debouncedFunction = debounce(async () => {

        // use event value if you want in request
        const response: any = await axios.get(
          'https://jsonplaceholder.typicode.com/todos/1' + `?test=${event.target.value}`
        );

        if (response.data) {
          console.log('autocomplete results...')
        }


      }, 2000);
      debouncedFunction();


    } catch (error) {
      console.error(error);
    }
  }

  return (
    <div >

      <input
        value={inputValue}
        onChange={onSearchChange}
        placeholder="Search with autocomplete..."
      />

    </div>
  );
}

export default App;

The rest of displaying the autocomplete results is left for your app to display what better suits you

here is a link to the repo to download and tweak as you like

https://github.com/lalosh/stackoverflow-autocomlete-example

Sorry for being busy. 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM