0

I'm trying to fetch new data within .map because I need to iterate to get some data extracted, however, I'm running into issues when I'm trying to return data.

I'm either getting Promise or an Error object message.

When I do .then(), it gives me a Promise, but when I do async/await, it gives me an Error.

What would be the best approach?

async function getData(id) {
    const data = await fetch("api"+id);
    return await data.json();
}

async function getAnotherData(id) {
    const data = await fetch("different-api"+id);
    return await data.json();
}

export const getServerSideProps = async (context) => {
    const firstData = await getData("26");
    return {
        props: { 
            firstData
         }
    }
}

const App = ({ 
    firstData
}) => {
    return (
        {firstData.map(function(item) {
            const id = item.id

            const promiseReturn = getAnotherData(id).then(item => console.log(item)})
            
        }}
    )
}

export default App;

This way allows me to get the data when I console.log, but I can't actually get the data to be extracted. I wanted to place the data into promiseReturn

if I replace my .map using async/await like so:

    // adding async/await here
    {firstData.map(async function(item) {
        const id = item.id

        // this gives the error:

        
        const errorReturn = await getAnotherData(id);
    }}

I'll get the Error message:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

So my issue is, I can't get data out of API because I'm trapped with 2 issues.

felmez
  • 90
  • 10
hellomello
  • 8,219
  • 39
  • 151
  • 297
  • 1
    Not sure that you can use promise into the return of your component. This should be placed in a `useEffect` – devpolo Feb 12 '23 at 17:43

0 Answers0