Nobody seems to be able to help me with this and I am really unsure.
I am using React-Select drop down and doing an async call to get data from an API.
Here is my type :
type Person = {
value: string;
label: string;
};
Here is my promise for the data api :
const fetchDropDown = async () : Promise<Array<Person>> => {
try {
const stuff = await dynamicsWebApi.retrieveAll("accounts",["name"]);
const records = stuff.value;
const options = records?.map<Person>(d => ({
"value": d.name,
"label": d.name
}));
console.log(options)
return options as Person[]
} catch (error) {
if (error) {
console.log(error)
throw(error)
}
}
}
And here is my react component :
<div>
<AsyncSelect
cacheOptions
defaultOptions
loadOptions={fetchDropDown}
/>
At the top of the promise on this line :
const fetchDropDown = async () : Promise<Array<Person>> => {
I am getting the error :
Function lacks ending return statement and return type does not include 'undefined'
I know I am nearly there but I just cannot seem to get this final bit working so in the drop down I can see my rows from the API.
I need someone who truly knows the stuff to help me along with this.
So to get the component to drop down with the rows, I need it to be in a value/label pair and that's why I have gone with the .map command.
Can anyone help ? Thanks
CodePudding user response:
I had some similar issues and this knew to help. What happens is you specified output and try catch goes to error and returns something else.
const fetchDropDown = async () : Promise<Array<Person>> => {
try {
const stuff = await dynamicsWebApi.retrieveAll("accounts",["name"]);
const records = stuff.value;
const options = records?.map<Person>(d => ({
"value": d.name,
"label": d.name
}));
console.log(options)
} catch (error) {
if (error) {
console.log(error)
throw(error)
}
}
return options as Person[]
}
CodePudding user response:
You are getting this error because you have an un-accounted for scenario.
There are 3 possible scenarios here:
If we don't end up in the catch block the function returns
options as Person[]
-> this is okIf we do end up in the catch block and
error === true
we throw and error -> this is okIf we do end up in the catch block and
error === false
we do nothing -> this is not ok
Meaning that you should also account for the 3rd scenario, and that's what the error is telling you.
We can either return a value or throw an error, either way, needs to be handled.