Trying to return a promise for React-Select dropdown - typescript react

Viewed 39

So far no luck on this problem on this site. Someone who knows there stuff hopefully can help.

I have a type here :

type Person = {
  value: string;
  label: string;
};

And I have a block of code as promise here which gets the data from the api - then it transforms it to the correct type of array for the react component and then I hope to return it using the return command in a promise - like so :

const fetchDropDown = async () : Promise<Array<Person> | string>  => {
  try {
  const stuff = await dynamicsWebApi.retrieveAll("accounts",["name"]);
  const records = stuff.value;
  const options = records?.map(d => ({
    "value": d.name,
    "label": d.name
  }));
    console.log(options)
    return options
    } catch (error) {
      if (error) {
        console.log(error)
      }
    }
  }

But it is giving me all sorts of errors :

on the return options line

Type '{ value: any; label: any; }[] | undefined' is not assignable to type 'string | Person[]'. Type 'undefined' is not assignable to type 'string | Person[]'

I think it is because it is an array that I am passing back and the Person type is not an array, but I am the first to say I don't know much about typescript.

Also on the react component itself it is error where I am putting the load options

  <div>
       <AsyncSelect
          cacheOptions
          defaultOptions
          loadOptions={fetchDropDown}
        />

Any help Please!

1 Answers

Try this:

const fetchDropDown = async () : Promise<Array<Person> | undefined >  => {
  try {
  const stuff = await dynamicsWebApi.retrieveAll("accounts",["name"]);
  const records = stuff.value;
  const options = records?.map(d => ({
    "value": d.name,
    "label": d.name
  } as Person));
    console.log(options)
    return options
    } catch (error) {
      if (error) {
        console.log(error)
      }
    }
  }
Related