I have a problem with React Select. I'm using axios get method to get a data to dropdown list and then i want to show it in React Select.
I copied the code from the github example, but it doest work.
Get method:
onListaDzial = () => {
axios
.get("http://10.10.10.27:81/eWizjaAPI/api/Listy/GetSlownikDzialy?", { params : {rok : this.state.rok }, headers: { 'Authorization' : 'Bearer '+ this.state.token }})
.then(function (response) {
let options = response.data.map( category => ({ value: category.text, label: category.text}));
return { options };
})
.catch(error => this.setState({ error, }));
}
React select code in render
<Select name="form-field-name" options={options} />
You will need to set the state of the component in order to use it within the render function. Also you need to use a arrow function within .then
else the this context is wrong!
onListaDzial = () => {
axios
.get("http://10.10.10.27:81/eWizjaAPI/api/Listy/GetSlownikDzialy?", { params : {rok : this.state.rok }, headers: { 'Authorization' : 'Bearer '+ this.state.token }})
.then((response) => {
let options = response.data.map( category => ({ value: category.text, label: category.text}));
this.setState({options});
}).catch(error => this.setState({ error, }));
}
and in render
<Select name="form-field-name" options={this.state.options} />
You could also rewrite the onListaDzial
function to async/await like following:
onListaDzial = async () => {
const res = await axios.get("http://10.10.10.27:81/eWizjaAPI/api/Listy/GetSlownikDzialy?", { params : {rok : this.state.rok }, headers: { 'Authorization' : 'Bearer '+ this.state.token }}).catch(error => this.setState({ error, }));
let options = res.data.map( category => ({ value: category.text, label: category.text}));
this.setState({options});
}