Home > Mobile >  How to use fetched data with Next.js and TypeScript?
How to use fetched data with Next.js and TypeScript?

Time:09-29

I am new to Next.js and TypeScript. I am trying map() over the data from JsonPlaceholder

My getStaticProps:

export const getStaticProps: GetStaticProps = async () => {
    const res = await fetch(`https://jsonplaceholder.typicode.com/users`)
    const data = await res.json()
    return {
        props: { auth0Data: data },
    }
}

My NextPage:

interface Auth0DataProps {
    id: number,
    name: string,
    username: string,
}

type Props = {
    auth0Data: Auth0DataProps
}

const Dashboard: NextPage<{ auth0Data: Props }> = ({ auth0Data }) => {
    console.log(auth0Data) // logs the data as an object
    return (
        <LayoutComponent title="User profile">
          {auth0Data.map(data=> ( // I GET AN ERROR
            ...
           )
        )
 }

The error I'm getting:

Property 'map' does not exist on type 'Props'

CodePudding user response:

The most common error is the wrong interpretation of your fetched data. And as far as I can see, you get an object from your server, which means you can't use the array.map() function (MDN).

Typescript can't really help you there as it interprets your code not during runtime but on compile time. As a result, you have to make sure that the received data matches the specified types.

CodePudding user response:

If the data you're passing through the auth0Data prop is an array, then you're typing the Dashboard component incorrectly - auth0Data should be an array of Auth0DataProps, and NextPage should receive Props type as the generic.

type Props = {
    auth0Data: Auth0DataProps[]
}

const Dashboard: NextPage<Props> = ({ auth0Data }) => {
    // Remaining code
}
  • Related