What is the best way to integrate retrieved data into Next.js with TypeScript?

Hello everyone! I recently started working with Next.js and TypeScript. Currently, I'm attempting to use the map() function on data fetched from JsonPlaceholder API.

Here is my implementation for getStaticProps:

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

This is how I defined my NextPage component:

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

type Props = {
    auth0Data: Auth0DataProps
}

const Dashboard: NextPage<{ auth0Data: Props }> = ({ auth0Data }) => {
    console.log(auth0Data) // outputs the data as an object
    return (
        <LayoutComponent title="User profile">
          {auth0Data.map(data=> ( // This line throws an error
            ...
           )
        )
 }

The error I encountered is:

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

Answer №1

In the event that your data being passed through the auth0Data prop is an array, it means you are incorrectly defining the Dashboard component - auth0Data should be an array consisting of Auth0DataProps, and NextPage should accept the Props type as a generic.

type Props = {
    auth0Data: Auth0DataProps[]
}

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

Answer №2

A common mistake often made is misinterpreting the data retrieved. It seems like you are receiving an object from your server, which prohibits the use of the array.map() function (MDN).

Typescript does not provide much assistance in this scenario as it interprets code during compile time rather than runtime. Therefore, it is crucial to ensure that the received data aligns with the specified types.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

Error encountered when providing valid data types as arguments in a React/Typescript function

I am facing an issue when passing a string variable to a function. To address this, I have created an interface called MyMessageProps where I declare the message as a string. Subsequently, the function MyMessage utilizes this interface to return with the ...

Create a TypeScript function that can be called and has an extended prototype definition

I am seeking to create a callable function foo() (without using the new operator) that will also include a property foo.bar(). The JavaScript implementation would be as follows: function foo() { // ... } foo.prototype.bar = function bar() { // .. ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. In contrast, highlighted near the red arrows is my attempt at using Winston to ...

I'm looking for a way to save my next-auth user session. This will allow me to utilize the user ID to access data in various routes

My objective here is to retain data upon user login, as this data contains an ID essential for fetching information in other routes. After a successful login, users are directed to the /home route where the stored ID is used to retrieve data. Initially, ev ...

How to implement loading an external script upon a page component being loaded in NextJS

I recently transferred an outdated website to Nextjs and I am having trouble getting the scripts to load consistently every time a page component is loaded. When navigating between pages using next/link component, the scripts only run the first time the ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

The page does not appear to be updating after the onClick event when using the useState hook

Having difficulty re-rendering the page after updating state using the useState hook. Although the state value changes, the page does not refresh. export function changeLanguage(props: Props) { const [languageChange, setLanguageChange] = React.useState( ...

In what way can I utilize const assertions to extract literal types from deeply nested objects?

Let's imagine I have a unique set of individuals: const group = { Alex: ['Ben', 'Chris'], Sarah: ['Dylan'], } as const; With the help of constant clarifications, I can define the specific types like so: type Parent = ...

One approach to enhance a function in Typescript involves encapsulating it within another function, while preserving

What I Desire? I aim to create a function called wrap() that will have the following functionality: const func = (x: string) => 'some string'; interface CustomObject { id: number; title: string; } const wrapped = wrap<CustomObject> ...

Transmitting image data (blob) from the frontend to the backend using Next.js and tRPC (T3 stack)

I'm currently facing a challenge in sending a leaflet map image from the backend to the frontend using the leaflet-simple-map-screenshoter library for capturing the image. The library returns a blob, which I need to transmit back to the backend and sa ...

Guide to inserting a custom image into an Icon in next js

For my Next.js 13 and Tailwind project, I am looking to customize a chat/messenger icon by filling it with an image of my choice. While attempting to use the Lucide React Messenger icon, I found that it only allows hex color values for filling, but I want ...

I keep encountering an error when trying to import an image from the asset folder in Next.js

After successfully creating a React app, I encountered an error when trying to incorporate all the files into a Shopify app where Next.js is present. import React, {createContext, useState} from "react"; import bag from &quo ...

When employing the caret symbol (^) in package.json, it fails to update the minor version

Within my package.json file, there is a line that reads as follows: "typescript": "^4.1.6", The presence of the caret (^) symbol indicates that npm should install a version of TypeScript above 4.1 if available. However, upon checking ...

Refreshing Components upon updates to session storage - Angular

Currently, I am in the process of developing a build-a-burger website using Angular. The ingredients and inventory need to be updated dynamically based on the selected location. Users can choose the location from a dropdown menu in the navigation bar. The ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. https://i.sstatic.net/EyTZE.jpg My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

Exploring the capabilities of the Next.js framework with the powerful Advanced Custom Fields Repeater

Having trouble implementing an ACF repeater field in my Next.js project. I have a block with a repeater field containing sub fields, and although I can retrieve the data, I'm unsure how to iterate through it. Below is a snippet of my JavaScript file: ...

What is the best way to add a 'Drawer' component into the 'AppBar' using React MUI within the Next.js framework?

My goal is to create an App bar with a 'hamburger' icon on the left that, when clicked, will display a Sidenav (drawer). I am working with React Material and Next.js (App router) and need to have the app bar and drawer as separate components, hea ...

"Encountered a TypeScript error (2345) when using customElements.define() in Lit 2

When we upgraded various lit-Components to version 2.1.1 "lit": "2.1.1", a TypeScript error surfaced: The argument 'typeof MyComponent' cannot be assigned to a parameter of type 'CustomElementConstructor'. The &apo ...