M
M
Maxim2020-04-17 09:19:59
JavaScript
Maxim, 2020-04-17 09:19:59

Why is null passed instead of state?

There is a component.
In ComponentDidMount we get data (an array of objects), which we then write to state.
On the first render, the state is null and, accordingly, the error "TypeError: Cannot read property 'map' of null" is thrown. Which is quite logical. What? I do not understand? What should I do to render the received data?

export default class Main extends Component {
  service = new PostServise();
  state = {
    data: null
  };

  componentDidMount() {
    this.service
      .getAllPost()
      .then( (data) => {
        console.log(data);
        this.setState({
          data: data
        });
      });
  }

  renderPosts(arr) {
    return arr.map(({id, title, text}) => {
      return (
        <section className = 'main__post post'
                  key = { id }>
          <a className = 'post__link' href='viewpost.html'>{title}</a>
          <p className = 'post__text'>{text}</p>
      </section>
      )
    });
  }

  render() {
    const item = this.renderPosts(this.state.data);
    return(
      <div>
        {item}
      </div>
    );
  }
};

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
McBernar, 2020-04-17
@mironov_m

In React, a popular technique is

{ this.state.value && ( <>{this.state.value}</> ) }

V
Vladimir, 2020-04-17
@HistoryART

I think you mistyped:

service = new PostServise() => service = new PostService()

P
Pavel Didenko, 2020-04-17
@Dasslier

The problem is that you don't understand the life cycle well. The componentDidMount method is called AFTER the first render, and you pass null in the render, which is why you get this error.
Study the life cycle and for a better understanding paste the consolelog into render , componentDidMount , ComponentDidUpdate , componentWillUnmount and see what and when it fires

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question