Reputation: 3
I have an error that cannot read property 'map' of undefined TypeError I want show menus.name list after mapping menus. I don't understand this error
This is my ssr-test.js code
import Layout from "../components/Layout";
import axios from "axios";
export default class SSRTest extends React.Component {
static async getInitialProps({ req }) {
const response = await axios.get("http://localhost:9000/menus");
return { menus: response.data };
}
render() {
const { menus } = this.props;
const menuList = menus.map(menu => <li key={menu.id}>{menu.name}</li>);
return <ul>{menuList}</ul>;
}
}
Next is my db.json code
{
"menus": [{
"id": 1,
"name": "연어",
"picture": 123,
"caption": "존맛탱",
"url": 123
},
{
"id": 2,
"name": "돈까쓰",
"picture": 123,
"caption": "존맛탱",
"url": 123
},
{
"id": 3,
"name": "김치볶음밥",
"picture": 123,
"caption": "존맛탱",
"url": 123
}
]
}
This is error code..
Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
at SSRTest.render (pages/ssr-test.js:11:0)
at finishClassComponent (node_modules/react-dom/cjs/react-dom.development.js:13537:0)
at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:13500:0)
at beginWork (node_modules/react-dom/cjs/react-dom.development.js:14089:0)
at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:16415:0)
at workLoop (node_modules/react-dom/cjs/react-dom.development.js:16453:0)
at renderRoot (node_modules/react-dom/cjs/react-dom.development.js:16532:0)
at performWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:17386:0)
at performWork (node_modules/react-dom/cjs/react-dom.development.js:17294:0)
at performSyncWork (node_modules/react-dom/cjs/react-dom.development.js:17266:0)
Upvotes: 0
Views: 10730
Reputation: 254
I have been experiencing the same issue for past few days, from my experience what I think is that since there is a request to external sources in the getInitialProps() function, it returns an unresolved javascript object.
When we directly try to use the data inside the objects, it works. But .map() doesn't work.
NOTE : When printing the data to the console:
Initial State
After Expanding ( the blue 'i' represents that the data was evaluated after expanding ), hence we were unable to use it in .map()
Upvotes: 1
Reputation: 420
Firstly check of everything is OK with your fetch url and you request is working. Secondly you should extract you response data one lever deep, because you are assign an object instead of array of data.
static async getInitialProps({ req }) {
const response = await axios.get("http://localhost:9000/menus");
return { menus: response.data.menus };
}
Upvotes: 3