Why is This React Code Unreachable When Its an Array But Works for a Single Object

311 views Asked by At

Hi I want to use the map function to iterate over my data and populate a table in React. Using State I set my variable to an empty array but when I come to Map it the code is unreachable and I have no idea why.

Note: If I map an individual object in the constructor it works perfectly.

Updated

SOLVED! _ Sorry guys - My Mistake - I missed the second render() { which obviosly caused the code to become unreachable

Eriks Solution Worked but the Get Request is Still not firing - I understand that is a seperate issue...

How do we clean up this post? I'm just new here?

2

There are 2 answers

1
Erick On

This is because of the return in the map function and the render not returning anything.

import { Container, Table } from "react-bootstrap"
import RestClient from "../../common/RestClient"
import AppUrl from "../../common/AppUrl"

export class ViewAllSubbies extends Component {
  constructor() {
    super()
    this.state = {
      subbieData: []
    }
  }

  componentDidMount() {
    RestClient.GetRequest(AppUrl.AllSubbies).then(result => {
      this.setState({ subbieData: result })
    })
  }

  render() {

    const Subbies = this.state.subbieData;
    return (Subbies.map(item=> {
      return (<tr>
        <td>{item.id}</td>
        <td>{item.contractor_name}</td>
        <td>{item.contractor_type}</td>
        <td>{item.contractor_email}o</td>
        <td>{item.contractor_phone_number}</td>
      </tr>)
    }))
  } 

Please refer to the updated code.

1
Dawood Ahmad On

that's because you have given the array "Subbies" and map item "Subbies" the same names, just give map item a different name like "Subby" or something else. and also the values should be map item's values like this:

const Subbies = this.state.subbieData;
const SubbieTable = Subbies.map(subby=> {
  return
  <tr>
    <td>{subby.id}</td>
    <td>{subby.contractor_name}</td>
    <td>{subby.contractor_type}</td>
    <td>{subby.contractor_email}o</td>
    <td>{subby.contractor_phone_number}</td>
  </tr>
})