2

imageThe images shows my data stored in Firebase,it is a Json data.

Error is type Error: Cannot read property 'date' of undefined, what I am doing wrong???

I want to access date from it, on clicking button show_data , date should be returned,but on the user screen.

I am unable to print it on console and user screen

import React, { Component } from "react"; //, { useState }
import "./styles.css";
import axios from "axios";

class App extends Component {
  state = {
    getData: "Date"
  };

  reloadHandler = () => {
    axios.get("https://loco-97cba.firebaseio.com/.json").then((res) => {
      const arrayObj = Object.entries(res.data).map((e) => [e[0]]);
      const arrayObj1 = Object.entries(res.data).map((e) => [e[1]]);
      console.log(arrayObj);
      console.log(arrayObj1);
      this.setState({
        getData: arrayObj1[1].date
      });
      console.log( "date", this.state.getData)
      // }
    });
  };

  render() {
    return (
      <div className="App">
        <button
          onClick={() => {
            this.reloadHandler();
          }}
        >
          GET_DATA
        </button>
        <br/>
        <br/>
        <div style={{border:"black 1px solid",height:"100px"}} >{this.state.getData}</div>
      </div>
    );
  }
}

export default App;
Nihal Chandwani
  • 146
  • 1
  • 9

1 Answers1

1

Below statement will not log your dates into the console. Because setState will take time to actually reflects the values.

console.log( "date", this.state.getData)

Instead what you can do is move that console.log into the render method so you can see the updated values each time.
One more thing you are not able to see the result on the webpage because your state this.state.getData is an array.

<div style={{border:"black 1px solid",height:"100px"}} >{this.state.getData}</div>

If you want to keep it as an array then you can map over it and print the data like this.

{this.state && this.state.getData.map(date => <div style={{border:"black 1px solid",height:"100px"}} >{date}</div>)}

Otherwise, just try this -

<div style={{border:"black 1px solid",height:"100px"}} >{this.state.getData[0]}</div>

See this -

Sagar Darekar
  • 982
  • 9
  • 14