0

I have a webpage that pulls launch data from the SpaceX graphQL API, and then renders that data as a list. Users can click on a specific launch in that list that takes them to a 'details' page about that particular launch.
On the details page, I'm trying to extract a paramter from the URL using useRouter. Upon logging out this paramter value to the browser, I've found that it's initially logged as undefined, and then shortly after the correct data is logged - I'm asusming this is some sort of async issue.
I need the paramater for another API call, however I can't do that if it's not loading instantly - I've tried putting it into an async/await function but it hasn;t helped. Suggestion?

Details page: [paramter].js

import { useRouter } from 'next/router'
import { useContext,useState,useEffect } from 'react'
import { LaunchContext } from '../spacexContext'

const Items =   () => {
    const data =  useContext(LaunchContext)
    const router = useRouter()
    console.log(router.query.paramter)
    
        const getLaunchData = async () => {
            const [ launchData,setLaunchData ] = useState([])
            let parameters = await router.query.parameter
            setLaunchData(parameters)
            return launchData
        }

       const parameter =  getLaunchData()


    return ( 
        <div>
            this is items
        </div>
     );
}
 
export default Items;

Included a screen shot of the console in the browser when I redirect to /launchesPast route

Errors in the console

Josh Simon
  • 159
  • 1
  • 10
  • 27

1 Answers1

2

This is caused by how Automatic Static Optimization works:

Pages that are statically optimized by Automatic Static Optimization will be hydrated without their route parameters provided, i.e query will be an empty object ({}).

After hydration, Next.js will trigger an update to your application to provide the route parameters in the query object.

You can return null when the parameter is undefined, or you can try some solutions shared in this issue: https://github.com/vercel/next.js/discussions/11484