Reputation: 5
Whats wrong with my code?
import React, { Component } from "react";
// import {connect} from 'react-redux';
// import List_items from './list_items';
// @connect(item => ({data: state.example.data}))
class Home extends React.Component {
constructor(){
super();
this.state = {
dataOperations: [],
};
}
componentDidMount(){
fetch('http://127.0.0.1:8000/Selectallbarang/?format=json')
.then(results => {
return results.json();
}).then(data => {
let dataOperations = data.results.map((idk) => {
return(
<h1 key={idk.results}>
{idk.harga_satuan}
</h1>
)
})
this.setState({dataOperations: dataOperations});
console.log("state", this.state.id);
})
}
I get the error code like below
Unhandled Rejection (TypeError): Cannot read property 'map' of undefined (anonymous function)
C:/Users/kurniawan/django/shemura/frontend/src/home/Home.js:23
20 | .then(results => {
21 | return results.json();
22 | }).then(data => {
> 23 | let dataOperations = data.results.map((idk) => {
24 | return(
25 | <h1 key={idk.results}>
26 |
View compiled This screen is visible only in development. It will not appear if the app crashes in production. Open your browser’s developer console to further inspect this error.
Upvotes: 0
Views: 1343
Reputation: 93223
Replace data.results.map
by (data.results || []).map
Because this error means data.results
is undefined, then data.results.map
is property (method) cannot be read from that undefined.
There are many ways to handle that, however, I assume I gave you the most elegant way.
Upvotes: 6