Z
Z
Zhanna_K2020-09-24 18:56:05
React
Zhanna_K, 2020-09-24 18:56:05

What is the best way to make asynchronous requests in a React container component so that updated props come to the presentation component?

Good evening! Faced such a problem.

  • I need to display a list of projects that I store in a MongoAtlas cluster.
  • Through axios, I make a request to the server, upload data to the store. Then I try to pass this data to the component through connect() .
  • Everything works, but the data comes after the render() method is called . Therefore, the component is not rendered and throws an error.
    How to fix it?


I tried to make a request in componentDidMount() , but this method does not work, because the component was not rendered.
I make a request via componentWillMount( ), but I read that you can't do that... and the props still come empty...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zhanna_K, 2020-09-24
@Zhanna_K

As a result, it turned out to solve the problem using getDerivedStateFromProps. I compare the state
with the incoming props and update the state. Then I pass the state data as props to children

static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.projects !== nextProps.projects) {
    }
    return {
      projects: nextProps.projects,
    };
  }

If you know another elegant solution, please write a comment.
PS 10 minutes later I found a silly bug in the code, so guys, everything works as it should work well without what I wrote above.
Just an asynchronous request in componentDidMount() and all props are automatically updated.
Such simple things should work without any frills.
So be careful, not like me :)

V
Vladislav Lyskov, 2020-09-24
@Vlatqa

Everything works, but the data comes after the render() method is called. Therefore, the component is not rendered and throws an error.
How to fix it?

async await

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question