I am very puzzled on a relatively trivial question.
I wish to retrieve data from my database using a node.js API call, the API call is working perfectly fine, and I am able to successfully retrieve data in my .then(()=>{}) function in my promise.
However the issue I am having is that I wish to use this data outside of the scope of the "then" particularly I want to map the results into a ListViewItem in my front end.
Here is the code
import {Box, Button, Grid, List, ListItem, ListItemButton, ListItemText} from "@mui/material"
import {useEffect} from "react";
import axios from "axios";
function RequestApproval() {
let dataFromDb =[]
const result = axios.get("http://localhost:3001/all-user-addresses").then((response) => {
console.log(response.data.result); //This works perfectly fine
dataFromDb.concat(response.data.result)
})
console.log(dataFromDb) //This list always appears empty.
const data = result;
return (
<div style={{display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh'}}>
<Box style={{borderRadius: '16px', backgroundColor: '#6ea6be'}}>
<List sx={{width: '600px', maxWidth: '1000px'}}>
{//My listview items from my API call go over here
}
</List>
</Box>
</div>
);
}
export default RequestApproval;
CodePudding user response:
you need to use state for this problem. at first
const [list,setList]= useState([])
then in your RequestApproval function replace
dataFromDb.concat(response.data.result)
by this
setList(response.data.result)
and your jsx map through the list array.
CodePudding user response:
You can simply utilize the useState
hook.
Replace let dataFromDb =[]
with const [data, setData] = useState()
.
Then instead of using dataFromDb.concat(response.data.result)
use setData(response.data.result)
.
For more information look at the official docs