I've been trying to deconstruct an object. The object comes via json as a result of single column select from the database.
//api
export const fetchNames = async() => {
try {
const data = await axios.get("http://localhost:5000/names");
return data;
} catch (error) {
return error
}
}
//function call
const [fetchedNames, setfetchedNames] = useState([]);
useEffect(()=>{
const fetchApi = async () => {
fetchedNames(await fetchNames());
}
fetchApi();
console.log(fetchedNames);
})
result: data:Array(23)
0:{name:"adams"}
Expected is an array of all names. [ADAMS, SIMON, ...]. The array will be use in a NativeSelect and will be display as frontend selection.
Approach i did that resulted to my expected output.
export const fetchNames = async () =>{
try{
const response = await fetch(`http://localhost:5000/towns`);
const jsonNames = await response.json();
return jsonNames;
}catch(error){
return error;
}
}
const [fetchedNames, setFetchedNames] = useState([]);
useEffect(()=>{
const fetchApi = async () =>{
setFetchedNames( await fetchNames());
}
fetchApi();
},[]);
Then, i did the mapping. {fetchedNames.map((Names,i) => (<option key={i} value {Names.name}>{Names.name}))}