TypeError: Cannot read property '0' of undefined when using state

I am having an issue with trying to pass the Axios response data to the components. In the console log during the componentDidMount it will log just fine, but for the quote and value taking state it is saying it cannot read property 0 of undefined.

I am thinking it has something to do with the data not being loaded before the dom rendering causing the error. However everything I am reading online seems to say that this is the correct way to handle it.

import React, { Component } from 'react';
import Header from './components/header.js';
import Home from './components/home.js';
import './App.css';
import Axios from 'axios';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sqlClosed: [],
      sqlClosedRebill: [],
      sqlPotential: [],
      sqlPotentialRepeat: [],
      sqlRebill: [],
      sqlRepeat: [],
      loaded: false,
    };
  }

  componentDidMount() {
    Axios.get('url', {
      headers: { 'Content-Type': 'application/json' },
      data: {},
    })
      .then((response) => {
        this.setState({
          sqlClosed: response.data.result.sqlClosed,
          sqlClosedRebill: response.data.result.sqlClosedRebill,
          sqlPotential: response.data.result.sqlPotential,
          sqlPotentialRepeat: response.data.result.sqlPotentialRepeat,
          sqlRebill: response.data.result.sqlRebill,
          sqlRepeat: response.data.result.sqlRepeat,
        });
        this.setState({ loaded: true });
        console.log(this.state.sqlClosed.recordset[0].sQuoteType);
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render() {
    return (
      <>
        <Header />
        <Home
          quote={this.state.sqlClosed.recordset[0].sQuoteType}
          value={this.state.sqlClosed.recordset[0].nCount}
        />
      </>
    );
  }
}

export default App;

1 thought on “TypeError: Cannot read property '0' of undefined when using state”

  1. The trouble is that on first render your arrays are all empty. I do see that you have a flag there (loaded) to indicate when the data was loaded. Why not put it to good use?

      render() {
        return (
          <>
            <Header />
           {this.state.loaded && 
            <Home
              quote={this.state.sqlClosed.recordset[0].sQuoteType}
              value={this.state.sqlClosed.recordset[0].nCount}
            />
           }
          </>
        );
      }
    
    Reply

Leave a Comment