Maria Minh Maria Minh - 1 month ago 6
React JSX Question

react-select async doesn't work

const formatData = ((els) => {
console.log("ELS : ", els.data); /* Get Undefined */
return _.each(els, (el) => ({
label: el.first_name,
value: el.id,
}));
});


const fetchOptions = ((input, callback) => {
return fetch("http://reqres.in/api/users")
.then((res) => {
callback(null,
{
options: formatData(res.json())
}
)
}).then((json) => {
return {options: json};
});
});


Based to this documentation, I'm trying to get data and set it to match the format required by
loadOptions
property of
<Select.Async ... />
. As I mentioned above, I got
Undefined
for els.data. Can anyone tell me what I'm doing wrong ?

Answer

res.json() is asynchronous. It returns a Promise, so handle in the next then.

const fetchOptions = ((input, callback) => {
  return fetch("http://reqres.in/api/users")
    .then((res) => {
      return res.json();
    }).then((json) => {
      // formatData(json);
    });
});