I'm working on a website that allows you to search for people in a database based on location. Initially, the dropdown menu (select) is populated with provinces that available people are in. I'm trying to use a mongo query to populate that select menu. But when I try to get the values outside the function, it does not work and the select menu turns up empty.
import * as React from "react";
import axios from "axios";
const Locations = () => {
let options = null;
function axiosTest() {
// This is a server link i created that runs a query that returns distinct provinces from the database
const promise = axios.get("/api/v2/people/provinces");
const dataPromise = promise.then(result => result.data).then(data => {console.log(data);return data;});
// The console.log() above displays all the objects that are in the query given by the server link in an array
// e.g. ['British Columbia', 'Alberta', 'Saskatchewan', etc.]
}
var type = axiosTest();
console.log(type); // now it displays it as "undefined"
if (type) {
options = type.map((el) => <option key={el}>{el}</option>);
}
return (
<div
style={{
padding: "16px",
margin: "16px",
}}
>
<form>
<div>
<select>
{
/** This is where we have used our options variable */
options
// and the select menu is shown as blank, because it doesn't have any options to fill it with
}
</select>
</div>
</form>
</div>
);
};
export default Locations;
Can someone please help me get this to work? Is it something to do with Threads and Concurrency? I'm unfortunately rusty at that.