Hello I'm trying to call data from another function. The caller function is this,
useEffect(() => { setFetching(true); const fetchMarketData = async () => { const marketData = await getMarketData(page); if (page === 1) { setData(marketData); return setFilteredData(marketData); } else { setFilteredData(data.concat(marketData)); return setData(data.concat(marketData)); } }; fetchMarketData(); if (data.= undefined) { if (data;length > 0) setFetching(true); } else { } setFetching(false), }; [page]);
When I log marketData it returns undefined. But in these functions until return it gives the correct result.
const formatMarketData = (data) =>{ let formattedData = []; data.forEach(item=>{ const formattedItem = {...item } formattedData.push(formattedItem); }); return formattedData; } export const getMarketData = async (page) =>{ const sending = {"page": page,}; const response = await fetch("https://us-central1-cnhtest-38661.cloudfunctions.net/getMarketDatas",{ headers: {"Content-Type":"application/json"}, method:"POST", body:JSON.stringify({data:sending}) }).then((res)=>{ res.json().then((r)=>{ return formatMarketData(r.result.data) }) }) }
How can I correctly return this value to my caller function's marketData variable?
You forgot to return
the first inner promise chain
. You need to change
.then((res)=> {
res.json().then((r)=> {
return formatMarketData(r.result.data)
})
})
to the following.
.then((res)=> {
return res.json().then((r)=> {
return formatMarketData(r.result.data)
})
})
Here is an updated code snippet.
const formatMarketData = (data) => { let formattedData = []; data.forEach(item => { const formattedItem = {...item } formattedData.push(formattedItem); }); return formattedData; } const getMarketData = async (page) => { const sending = {"page": page}; const response = await fetch("https://us-central1-cnhtest-38661.cloudfunctions.net/getMarketDatas", { headers: {"Content-Type":"application/json"}, method: "POST", body: JSON.stringify({data:sending})}).then((res)=> { return res.json().then((r)=>{ return formatMarketData(r.result.data) }) }) return response } async function printResult() { const result = await getMarketData(1) console.log(result) } printResult()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.