I cant seem to return the value of this API call in javascript to my react component. I have a java script file that calls an API. In the js file, results are returned but when I call the js function in useEffect in my react component, it returns undefined.
export function ordersData() {
const partner_code = localStorage.getItem('partner_code')
let items = []
let data = []
let isLoaded = false
let error = ''
fetch('xxxxxxxxxxxx' + process.env.REACT_API)
.then(res => res.json())
.then((result) => {
for (let instance in result['docs']) {
let payload = (result['docs'][instance])
payload.id = instance
payload.timestamp = shortMonthYear(payload.timestamp)
data.push(payload)
}
items = data.reverse()
}, (err) => {
isLoaded(true)
error(err)
})
}
Here is my rect component
export default function OrdersChart() {
const [payload, setPayload] = useState([])
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
setPayload = ordersData()
console.log(payload)
}, [])
........
The variable payload is empty
ordersData().then(payload => console.log(payload)). Also you should return fetch from ordersData function.