Rohan
Rohan

Reputation: 109

Need to display the array list on frontend

I trying to display the list using map function javascript but I am getting error saying "TypeError: Cannot read property 'map' of undefined".

import React, { Component } from 'react'
import constants from './Constants'
import axios from 'axios'

class Home extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      value: 0,
      results: {},
    }
    this.handleClick = this.handleClick.bind(this)
    this.input = React.createRef()
  }

  handleClick = event => {
    this.setState({ value: this.input.current.value })
    event.preventDefault()
  }

  componentDidMount() {
    console.log('componnet did mount')
    const that = this
    axios.get('https://reqres.in/api/users').then(function(response) {
      that.setResults(response.data)
    })
  }

  setResults(data) {
    this.setState({ results: data })
  }

  render() {
    let newvalue = this.state.value
    let obj = this.state.results
    console.log(obj)
    let latestvalue =
      constants.MONTHS[newvalue] == null
        ? 'invalid month'
        : constants.MONTHS[newvalue]
    return (
      <div className="home">
        <h1>Welcome to my portfolio website</h1>
        {obj.data.map(emp => (
          <tr>
            <td> </td>
          </tr>
        ))}
        Enter Month number <input type="text" ref={this.input} />
        <button type="button" onClick={this.handleClick}>
          {' '}
          submit{' '}
        </button>
        <p> Feel free to browse around and learn more about me.</p>
        Month is {latestvalue}
      </div>
    )
  }
}
export default Home

Need to display all the first names on DOM. I just need to display the first names in that array of object also recommend me which Javascript function best to use display data.

Upvotes: 0

Views: 552

Answers (2)

Piyush Zalani
Piyush Zalani

Reputation: 3934

Try to update following block of lines may help you:

{obj && obj.data && obj.data.map(emp =>
   <tr>
     <td> {emp.first_name}</td>
   </tr>
)}

Upvotes: 1

Alexei Darmin
Alexei Darmin

Reputation: 2129

When initializing the state, you need to describe the full shape of the object for TypeScript to understand it.

results : {
  obj: {
    data: null
  }
}

Upvotes: 1

Related Questions