I cant seem to return the value of this API call in javascript to my react ponent. 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 ponent, 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 ponent
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
I cant seem to return the value of this API call in javascript to my react ponent. 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 ponent, 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 ponent
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
Share Improve this question edited Mar 17, 2022 at 8:35 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Oct 28, 2021 at 11:41 lungulungu 872 silver badges10 bronze badges 1-
the API calls are asyncronous. To get value you should use .then on the Promise. So it'll be
ordersData().then(payload => console.log(payload))
. Also you should return fetch from ordersData function. – bazzas Commented Oct 28, 2021 at 11:46
3 Answers
Reset to default 5You need to use React hooks for API calls and store the data. You can use useEffect
hooks to call the API and use useState
for storing data in the state.
const { useState } = React;
function useFetchData() {
const [loading, setLoading] = React.useState([]);
const [data, setData] = React.useState([]);
React.useEffect(() => {
setLoading(true);
fetch("https://randomuser.me/api/?results=10")
.then((response) => response.json())
.then((responseJson) => {
setData(responseJson.results);
setLoading(false);
})
.catch((error) => {
console.error(error);
setLoading(false);
});
}, []);
return { loading, data };
}
function App() {
const { loading, data } = useFetchData();
if(loading){
return <p>Loading... </p>
}
return (
<div>
{data.map((item) => (
<div>{item.name.first}</div>
))}
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare./ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Cleanest way I found was this
Change parent ponent to this
useEffect(() => {
newFunctionName();
}, [])
async function newFunctionName(){
const response = await ordersData();
console.log(response)
// you can then set all your states directly in here
}
Change api call ponent to this.
export default async function ordersData() {
try{
const res = await fetch('xxxxxxxxxxxx' + process.env.REACT_API)
return res
} catch(err){
console.log(err)
return(err)
}
}
Now you have the response in the parent ponent and can set states from there instead.
You dont return anything in this function. You just push payload value in data, that a local variable. You can use state and set value by setState.