I am using the react-select component consuming data from an api-rest. The query and the return of the data works correctly. However, the following fails to load the options in the select
My developed code is as follows, from the html I call it like this:
<AsyncSelect cacheOptions defaultOptions loadOptions={this.loadRepuestos} />
Then I have my code for the loadRepuestos function, which is as follows:
loadRepuestos = (name) => {
if(name.length > 3 && this.state.peticionActiva !== true) {
const config = {
headers: { Authorization: `Bearer ${this.state.token['token']}` }
};
let url = API_REPUESTOS_FILTER + `?name=${name}`;
// console.log(this.state.token['token']);
this.setState({peticionActiva: true});
//seteo peticionActiva true para evitar que se desaten continuas peticiones
return axios.get(url,config)
.then(response => {
this.setState({peticionActiva: false});
let lista = response.data.data;
//armo el par {{value ... label.. } ......}
let options = lista.map(elemento => {
let item = {};
item.value = elemento.id;
item.label = elemento.name;
return item;
});
console.log(options);
// console.log({options: options});
return {options: options};
})
.catch(e => {
this.setState({peticionActiva: false});
if(e.response)
{
let error = '';
error = e.response.data.message;
console.log(error);
// this.setState({errorApi: error});
}
});
}
}
Printing to the console, the data comes in and looks like the following:
did you map it? the data is seen, but the select needs a mapping. I load it into another functional component const Options = ({ id,label}) =>{ return ( )}
I was able to solve the problem! I realized that when I mapped the pairs [ {id,label} ..... ] the id was left in the format of nro and not in string .
So I modified my mapping from how it was:
To the following form:
As you can see in the code above, I changed how the {id,value} pair is returned and uses an ecmascript string interpolation. In my environment I use babel and webpack, so that is automatically transpiled.
It seems crazy that the react-select package doesn't do an autocast. From now on I will take it into account because it is a difficult fault to find.