I want to populate dropdown menu with data from Rest API. I tried this:
<Select id="country-helper">
{array.map((element) => (
<MenuItem value={element.code}>{element.country}</MenuItem>
))}
</Select>
I created this service with Axios:
export interface CountriesDTO { country?: string; code: string; }
import axios, { AxiosResponse } from "axios";
import { CountriesDTO } from "./types";
const baseUrl = "http://localhost:8080/api";
export async function getCountries(): Promise<AxiosResponse<CountriesDTO[]>> {
return await axios.get<CountriesDTO[]>(
`${baseUrl}/merchants/onboarding/countries`
);
}
It's not clear how I can make the call into the React page. I tried this:
useEffect(() => {
const getData = async () => {
getCountries()
.then((resp) => {
console.log(resp.data);
})
.catch((error) => {
console.error(error);
});
};
}, []);
How I can populate the dropdown using the data from GET API call?
Just call your function getData from useEffect, you should also create state array to store your data.
const [array, setArray] = useState<CountriesDTO[]>([]); // <=== create state array
useEffect(() => {
getData(); // <=== call your function
}, []);
const getData = async () => {
getCountries()
.then((resp) => {
setArray(resp.data);
})
.catch((error) => {
console.error(error);
});
};