import { getCustomer } from './Customers';
let optionItems=[];
export const LOV: React.FunctionComponent = () => {
const loadCustomer = async () => {
const data = await getCustomer();
for (var i=0; i < data.value.length ; i)
{
optionItems.push({
key: data.value[i].CustomerId,
text: data.value[i].CustomerName
});
}
}
useEffect(() => {
loadCustomer();
}, [])
return (
<SearchableDropdown options={optionItems}/>
);};
Code in Customers.tsx
export const getCustomer = async (): Promise<any> => {
const response = await
$.ajax({
url: apiURL,
type: "GET",
headers: headers,
data: null,
cache: false,
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' accessToken);
}
})
.done( function (data) {
return data;
})
.fail(function (jqXHR) {
if (jqXHR.status == 401) {
promptAuth(jqXHR.getResponseHeader("WWW-Authenticate"));
}
else {
console.log("NOT 401");
}
});
return response;
}
I'm trying to populate a dropdown dynamically using a promise. I'm using Fluent-react Dropdown. getCustomer() loads values to const data. However, I can't see any values in the dropdown even though data is not null. Please help.
Fluent Dropdown => https://developer.microsoft.com/en-us/fluentui#/controls/web/dropdown
CodePudding user response:
Your optionsItems
need to be reactive. Try using useState
-hook
export const LOV: React.FunctionComponent = () => {
const [optionItems, setOptionItems] = useState([]);
const loadCustomer = async () => {
const data = await getCustomer();
const options = [];
for (var i=0; i < data.value.length ; i)
{
options.push({
key: data.value[i].CustomerId,
text: data.value[i].CustomerName
});
}
setOptionItems(options)
}
useEffect(() => {
loadCustomer();
}, [])
return (
<SearchableDropdown options={optionItems}/>
);};
CodePudding user response:
Please make sure your data.value[i].CustomerId
and data.value[i].CustomerName
are valid strings. You need to supply string, but it looks like your API call returns null there. After you fix this problem, together with Stutje's solution your app should start to work.