I try to follow some tutorial on youtube, and trying to build an admin dashboard the tutorial uses some dummy data for the portal
export const ordersData = [
{
OrderID: 10248,
CustomerName: 'Vinet',
},
{
OrderID: 345653,
CustomerName: 'Carson Darrin',
}, etc...
i try to replicate with the real API interaction
export const ordersData = fetch('API_URL', {method:"GET"})
.then(res => {
return res.json();
}).then(data => {
console.log(JSON.parse(data.body))
return JSON.parse(data.body)
})
but its seems not to work as expected, i try to compare the console.log with the directly input data they look the same in the console, both of them are shown as objects (typeof).
not sure which step is going wrong
CodePudding user response:
The problem is here you want to return
from fetch
browser API, which returns Promise
. If you really want to do it, for instance, instead of using useState
hook in React to call and save the response in component state, then you need to wrap your fetch
request into async
IIFE function and use await
statement to wait the async request to be fulfilled and the data to be resolved by Promise
. For more info, you can refer: JS Fetch API access return value
CodePudding user response:
write your fetch in an useEffect and set its response in a state
const [data, setData] = useState()
useEffect(() => {
fetch('API_URL', {method:"GET"})
.then(res => {
return JSON.parse(res);
}).then(response => {
setData(response)
})
}, [])