Home > Back-end >  How to pass parameters in Next.js without SSR?
How to pass parameters in Next.js without SSR?

Time:05-13

I try pass params as docs says here: https://nextjs.org/docs/routing/dynamic-routes

but the received params are not string??!! How could it be string array? I understand a bit when it is not exist, but how it could be array? I think this is a TypeScript magic, right?

I got this error:

Type 'string | string[]' is not assignable to type 'string'.

Why, router.query is not string or undefined?

import { useAppDispatch } from 'tikexModule/hooks'
import { getSoldPasses } from 'tikexModule/slice'
import { GetServerSideProps } from 'next'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import { string } from 'yup'

interface Props {
    organizationId: string
    passTypeId: string
}

function PassType(): JSX.Element {
    const dispatch = useAppDispatch()
    const router = useRouter()
    const { organizationId, passTypeId } = router.query

    //const organizationId = router?.query?.organizationId ?? undefined
    //const passTypeId: any = router?.query?.eventId ?? undefined

    useEffect(() => {
        if (organizationId && passTypeId) {
            dispatch(
                getSoldPasses({
                    organizationId, // <-- here
                    passTypeId,     // <-- here
                })
            )
        }
    }, [organizationId, passTypeId, dispatch])

    return <div />
}

export default PassType

CodePudding user response:

Just wrap the variable with String(). Basically from router.query , every variable is expected as string | string[]. You can pass query as string or list of string. So, in typescript it always returns string or string[] type data. Wrapping with String() will ensure data will be converted to string.

useEffect(() => {
        if (organizationId && passTypeId) {
            dispatch(
                getSoldPasses({
                    organizationId : String(organizationId), // <-- here
                    passTypeId: String(passTypeId),     // <-- here
                })
            )
        }
    }, [organizationId, passTypeId, dispatch])

CodePudding user response:

Since when using query parameters you can pass either 0 value, 1 value or multiple values for the same parameter.

http://www.youtube.com/action?id=a&id=b
http://www.youtube.com/action?id=a,b
http://www.youtube.com/action

So any query param you are extracting can either be a string or an array of strings. You can use the as keyword:

getSoldPasses({
                   organizationId : organizationId as string,
                passTypeId : passTypeId as string,
                })

  • Related