Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate React-Select with Rest API(Remote Data)

I'm very new to ReactJS, I'm trying to create a component with a list of values(should be fetched from an API) and should allow the search.

https://codesandbox.io/s/v1v1xp1xn3

Above example is working fine, but it uses local data. How to integrate with remote data. Upon every key press, it should hit API and fetch new data.

like image 727
Mahipal Reddy Avatar asked Jan 01 '23 06:01

Mahipal Reddy


1 Answers

What you're looking for is the React-Select AsyncSelect, as @Laura stated. The documentation is a little confusing. Here's the base example in the docs:

import React, { Component } from 'react';

import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from '../data';

const filterColors = (inputValue: string) => {
  return colourOptions.filter(i =>
      i.label.toLowerCase().includes(inputValue.toLowerCase())
  );
};

const promiseOptions = inputValue =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve(filterColors(inputValue));
    }, 1000);
  });

export default class WithPromises extends Component {
  render() {
    return (
      <AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} />
    );
  }
}

You'll see here that the loadOptions took a promiseOptions method that returned a Promise that eventually resolved to a list of options. If you replace the internals of that method with a fetch() (which returns a Promise), then when that request resolved to the list of options, those options would then be applied to the AsyncSelect.

const promiseOptions = inputValue => {
  const url = `my/remote/source${inputValue ? '?searchParam=' + inputValue : ''}`;
  return fetch(url)
           .then(response => response.json()) // my option list array?
           .catch(err => {
             console.log('some error', err);
           });
};
like image 89
Steve -Cutter- Blades Avatar answered Jan 05 '23 17:01

Steve -Cutter- Blades