Home > OS >  Async issues with Apollo graphql API call
Async issues with Apollo graphql API call

Time:04-15

In spacexContext.js,I'm making an API call the Spacex graphql API using the apollo client, then wanting to set the response to context. I'm logging the result when I use this context in other files, however I'm getting a pending promise instead of the returned data:

Promise {< pending>}

I'm using an async/await function to retrieve the data, and my understanding is that the data is resolved before being returned, so I'm confused about why this error is happening. Any suggestions?

spacexContext.js

import { useState,useEffect,createContext } from 'react'
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"

export const LaunchContext = createContext()


const getStuff = async () => {

  const client = new ApolloClient({
    uri: 'https://api.spacex.land/graphql/',
    cache: new InMemoryCache()
  })

  const { data } = await client.query({
    query: gql`
      query GetLaunches {
        launchesPast(limit: 10) {
          id
          mission_name
          launch_date_local
          launch_site {
            site_name_long
          }
          links {
            article_link
            video_link
            mission_patch
          }
          rocket {
            rocket_name
          }
        }
      }
    `
  });

  return data
}

const data =  getStuff()

const LaunchContextProvider = (props) => {

    return(
        <LaunchContext.Provider value = {data}>
            {props.children}
        </LaunchContext.Provider>
    )
}

export default LaunchContextProvider

index.js where the context is being used:

import { useContext } from 'react'
import { LaunchContext } from '../spacexContext'
import Link from 'next/link'


export const Home = () => {
  
  const data= useContext(LaunchContext)
  console.log(data) //pending promise instead of data
  return (
    <div>
      this is landing page
    </div>
  )
}

export default Home

CodePudding user response:

I solved this problem by enabling top level await in the next.config.js file:

module.exports = {
  webpack: (config, options) => {
    config.experiments = {
      topLevelAwait: true,
    };
    return config;
  },
};

..then used await on the function call in spacexContext.js :

const data = await getStuff()

CodePudding user response:

Any async function returns promise instead of data . The returned value is then resolved by thenable promise sturcture. eg.

async function fn(){
      return 5;
    }

function fn2(){
   return Promise.resolve(5)
   }



function fn3(){
  return new Promise(resolve=>resolve(5))  
  }

they all are equivalent or more like same

  • Related