search

React Select Search With Live Data Fetching

Comments:
Likes:
Shares:
Best Division

Best Division  @bestdivision

Published On - Last Updated -

React Select Search With Live Data Fetching From API

Create a file ReactSelectSearch.jsx

import React from "react";
import SelectSearch from "react-select-search";

function ReactSelectSearch() {
  return (
    <div>
      <SelectSearch
        options={searchState}
        // className="search_input css-scope jk-search-box"
        getOptions={(query) => {
          return axios({
            method: "POST",
            url: `search`,
            params: {
              q: query,
              // "limit": "2",
              // "offset": 1
            },
          })
            .then((response) => response.data)
            .then(({ data }) => {
              if (data.length) {
                updateSearchState(() =>
                  data.map((row, index) => ({
                    name: row.title,
                    value: index,
                    data: row,
                  }))
                );
              } else {
                updateSearchState(() => ({ name: "", value: "", data: "" }));
              }
              //return items.map(({title}) => ({ value: 'hello', name:title }))
            })
            .catch((error) => {})
            .finally(() => {});
          // return new Promise((resolve, reject) => {
          //     fetch(`https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${query}`)
          //         .then(response => response.json())
          //         .then(({ drinks }) => {
          //             resolve(drinks.map(({ idDrink, strDrink }) => ({ value: idDrink, name: strDrink })))
          //         })
          //         .catch(reject);
          // });
        }}
        placeholder="Search"
        search
        // onChange={setTitle}
        onChange={handleSearch}
        // onChange={onChange}
        emptyMessage={emptyMessage}
        // value='helllo'
        value={
          searchState.length &&
          searchState.find((obj) => obj.value === selectedValue)
        }
      />
    </div>
  );
}

export default ReactSelectSearch;

To implement a React Select search with live data fetching, you can use a library like **react-select** along with the **axios** library to make HTTP requests.

Here's an example:

  1. Install the **react-select** and **axios** libraries:
npm install react-select axios
  1. Import the required libraries in your React component:
import React, { useState, useEffect } from 'react';
import Select from 'react-select';
import axios from 'axios';
  1. Define a state for the selected option and an array for the options:
const [selectedOption, setSelectedOption] = useState(null);
const [options, setOptions] = useState([]);
  1. Use the **useEffect** hook to fetch the data from the API and update the options state:
useEffect(() => {
  axios.get('https://api.example.com/data')
    .then(res => setOptions(res.data.map(item => ({ value: item.id, label: item.name }))))
    .catch(err => console.error(err));
}, []);
  1. Render the **Select** component and pass the options and selected option state:
return (
  <Select
    value={selectedOption}
    onChange={setSelectedOption}
    options={options}
  />
);

By following these steps, you should have a working React Select search with live data fetching. The **useEffect** hook is used to fetch the data from the API when the component mounts and update the **options** state. The **Select** component is rendered with the options and selected option state as props, allowing the user to select an option from the list and triggering updates to the selected option state.

Similar Blogs
0 Commentssort Sort By

@abcd 1 days ago

Aquí los que apoyamos a Los del limit desde sus inicios..

dislike
reply
sdfsdf