V
V
Vlad2020-01-29 15:59:20
JSON
Vlad, 2020-01-29 15:59:20

Why is state not read in react?

I don’t understand why the state is not read
When I output to the console when the state is Initialized, everything is fine and everything is displayed
, but in the render the console does not see anything further than "form"

import React, { Component, Fragment } from "react";
import Form from "./components/Form.js";
class App extends Component {
  constructor() {
    super();
    this.state = {
      components: {},
      form: {},
      data: {}
    };
  }

  async componentDidMount() {
    let response = await fetch(
      "https://gist.githubusercontent.com/alexandrov-va/7f353ca822d074d7ce22d3af3d13696f/raw/0907091de6fedf6153cdb718f32a4215dc2c53cf/page.json"
    );

      let data = await response.json();
      this.setState({
        components: data.components,
        form: data.form,
        data
      });
      console.log(data.form.submit_button.text);

  }

  render() {
    console.log(this.state.data.form.submit_button.text)
    return (
      <Fragment>
        <Form  />
      </Fragment>
    );
  }
}
export default App;


it's just that if I'm rendering in view of the console.log(this.state.data) in the console, then it will calmly give the object in the console and without any errors, but if I enter console.log(this.state.data.form.submit_button.text) then the error TypeError: Cannot read property 'submit_button' of undefined is displayed

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
abberati, 2020-01-29
@abberati

Because the data comes in asynchronously and on the first render, the state is literally like this:

this.state = {
      components: {},
      form: {},
      data: {}
    };

you initialize it like this

M
Mikhail, 2020-01-29
@VK_31

Because fetch is an asynchronous function.
In the componentDidMount function, the this.setState function will be called only when the response from the request https://gist.githubusercontent ..... first, render will be called and this.state.form will show an empty object in the console, and later, after the request is executed, this.state.form will already take on a new value.

V
Vlad, 2020-01-29
@mrLVladV

it's just that if I'm rendering in view of the console.log(this.state.data) in the console, then it will calmly give the object in the console and without any errors, but if I enter console.log(this.state.data.form.submit_button.text) then the error TypeError: Cannot read property 'submit_button' of undefined is displayed

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question