When making an Axios API request in Next.js, an error is encountered stating that the property 'map' cannot be read as it is undefined

Hey there! I've been trying to fetch data from the API endpoint in my NextJs application using axios. However, whenever I try to map over the retrieved data, NextJs keeps throwing the error message "TypeError: Cannot read property 'map' of undefined". Does anyone have any suggestions on how to resolve this issue?

import axios from "axios"

const CosmeticsApi = ({cosmetics}) => {
  return (
    <div>
      {cosmetics.map(cosmetic =>(
        <div key={cosmetic.id}>
          <h4>{cosmetic.name}</h4>
        </div>
      ))}
    </div>
  )
}

CosmeticsApi.getInitalProps = async ctx => {
  try {
    const res = await axios.get('https://fortnite-api.com/v2/cosmetics/br');
    const cosmetics = res.data;
    return { cosmetics };
  } catch (error) {
    return {error};
  };
};

export default CosmeticsApi;

Answer №1

Just like before, you will need to access a different layer of data:

Remember, it's getInitialProps not getInitalProps. Oops, looks like you've caught me off guard.

CosmeticsApi.getInitialProps = async ctx => {
  try {
    const res = await axios.get('https://fortnite-api.com/v2/cosmetics/br');
    const cosmetics = res.data.data;  // <-- Make sure to access another data object here
    return { cosmetics };
  } catch (error) {
    return {error};
  }
};

Also don't forget to verify if the array exists before mapping through it:

const CosmeticsApi = ({cosmetics}) => {
  return (
    <div>
      {cosmetics && cosmetics.map(cosmetic =>(
        <div key={cosmetic.id}>
          <h4>{cosmetic.name}</h4>
        </div>
      ))}
    </div>
  )
}

See a working example here:

https://codesandbox.io/s/next-js-getinitialprops-redux-forked-83n8m?fontsize=14&hidenavigation=1&theme=dark

Answer №2

The issue has been successfully resolved after realizing a simple mistake.

It turns out that I had unknowingly violated a rule.

After consulting the documentation on next.js here, I discovered a crucial note:

Note: getInitialProps can only be utilized in pages, not in child components.

By fetching the data within index.js, I was able to retrieve the necessary information.

Prior to this, I had assumed that getInitialProps could be used in any component similar to componentDidMount.

It became apparent that this assumption was incorrect and led to the issue at hand.

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

A guide on transferring a Vue component to a custom local library

After successfully creating components using template syntax (*vue files), I decided to move common components to a library. The component from the library (common/src/component/VButton): <template> <button ... </button> </templat ...

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

Laravel throws an error message "expression expected" when trying to use the @

I keep encountering an issue when attempting to pass a variable from PHP code to JavaScript. Expression expected Here is the code snippet I am using in Laravel 7.0 : <script> let variable = @json($array); </script> Although the code still ...

Guide to setting up a TreeView with default expansion

When using a @mui TreeView, all nodes are initially collapsed by default. I am trying to figure out how to have all nodes expanded by default, but haven't been successful so far. I attempted to create a method called handleExpandAll, but it doesn&ap ...

Differences between JSX and creating instances of component classes

Could someone please clarify the distinction between the following two statements? let instance1 = new CustomComponent(); and let instance2 = <CustomComponent /> When checking in the Chrome debugger, I see the following: for instance1 CustomComp ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...

Implementing click events to control GSAP animations in Next.js

I'm having trouble figuring out how to pause/start an animation using GSAP in Nextjs. Specifically, I can't seem to work with a tl.current outside the useEffect hook within this component. My goal is that when I click on the first .imgWrapper ele ...

Unable to utilize await within a then statement to make a subsequent API call in a React application

Here is my scenario: I am making a call to one API, and in the `then` section of that API call, I am making another API call. The output of the first API will be passed as input to the second API. await axios .post(process.env + '/certificates/uplo ...

Establishing the module exports for the NextJS configuration file

I have explored different solutions for adding multiple plugins to the next.js config file, with composition being the suggested method. However, I am encountering issues with this approach. const Dotenv = require('dotenv-webpack'); const withSt ...

Strange yellow border appears when key is pressed in Quasar's QLayout

While working on a project with the quasar framework and electron.js, I encountered a strange bug where pressing a key causes the application frame to display a persistent yellow border. This border cannot be overridden, removed, or selected using devtools ...

Flex items maintaining their size when the window decreases

My goal is to arrange two plotly plots side by side within a CSS flexbox, with the ability to resize them as the window size changes. The issue I'm facing is that while the plots expand correctly when the window is enlarged, they fail to shrink when t ...

Employing plain Javascript (without the use of jQuery) to concatenate information from two JSON strings - encountering an error due to the absence of

Having a JSON stringified form data like this: {"name":"jack miller", "address":"123 main st"} I aimed to append more records but encountered an error saying "append is not a function." The desired outcome is to have both sets of records in this format: ...

Preventing Div items from rearranging during size transitions using toggleClass

When I click on an element with the ID "id", I use toggleClass to resize a div from 10px to 500px in width. This is done partly to show/hide content. However, the issue arises when the transition occurs and the contents of the div start rearranging, overfl ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

What is the process of converting code to JavaScript and React?

There are two methods defined as shown below. const handleClick = React.useMemo(() => !isRunning ? (items: string | string[]) => { if(Array.isArray(items)){ startRun({ items: items }); } else ...

Struggling with the proper state updating in React hooks when using dynamic naming conventions?

I am currently working with a react component that handles login requests to my server. This component is housed within a modal using Material UI. <TextField onChange={handleChange} autoFocus name="email" ...

Displaying and hiding the Angular <object> element

I am faced with a challenge involving managing files of various formats and creating a gallery with preview functionality. Everything works smoothly when clicking through items of the same format, like JPEGs. However, an issue arises when switching from vi ...

Is it possible to preload numerous extensive datasets in the background using ajax?

I'm currently in the process of developing a web application that operates solely on one page and revolves around presenting various table data in grids. There are approximately 30 different tables stored in the database, with any of them being access ...

How can I interpret a string with a specific format using JavaScript?

Input String: var json_data = "{0:'apple', 1:'bannana', 2:'guava'}"; Desired Output after parsing with JavaScript: var json_data = { columns: [{0:'apple'}, {1:'bannana'} ,{2:'guava'}] ...

When utilizing jQuery, I implemented this code but it does not display anything. I am unsure of the error within the code

When using jQuery, I implemented the following code snippet but it doesn't display anything. What could be causing this issue? // $.ajax({ // URL:"https://dog.ceo/api/breeds/image/random", // method:"GET", // ...