Home > Net >  Function that returns a promise, which is the set of options to be used once the promise resolves
Function that returns a promise, which is the set of options to be used once the promise resolves

Time:06-01

In my code loadOptions gives me the following error message " Function that returns a promise, which is the set of options to be used once the promise resolves." but I've already made some attempts in the code but without success. Can anyone help me understand this error presented in loadOptions ?

import { useState } from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import AsyncSelect from 'react-select/async';
import { fetchLocalMapBox } from '../api';


const initialPosition = {
    lat: -22.7532328,
    lng: -43.4563604
}

type Place = {
    label?: string;
    value?: string;
    position: {

        lat: number;
        lng: number;
    };
}

function OrderLocation() {

    const [address, setAddress] = useState<Place>({
        position: initialPosition
    })
    
    const loadOptions = async (inputValue: string, callback: (places: Place[]) => void) => {
        const response = await fetchLocalMapBox(inputValue);
      
        const places = response.data.features.map((item: any) => {
          return ({
            label: item.place_name,
            value: item.place_name,
            position: {
              lat: item.center[1],
              lng: item.center[0]
            },
            place: item.place_name,
          });
        });
      
        callback(places);
      };

<div className="filter-container">
                    <AsyncSelect 
                        placeholder="Digite um endereço para entregar o pedido"
                        className="filter"
                        loadOptions={loadOptions}
                        onChange={value => handleChangeSelect (value as Place)}
                    />

CodePudding user response:

The docs say

The loadOptions prop allows users to either resolve from a callback...

or resolve from a returned promise....

…but not both at once. If you are using an async function which returns a promise, resolve the promise with the options by returning the value. Do not accept a callback:

const loadOptions = async (inputValue: string) => {
    const response = await fetchLocalMapBox(inputValue);
  
    const places = response.data.features.map((item: any) => ({
        label: item.place_name,
        value: item.place_name,
        position: {
            lat: item.center[1],
            lng: item.center[0]
        },
        place: item.place_name,
    }));
  
    return places;
//  ^^^^^^
};
  • Related