Hold the button "React render" until you receive a request

I have a component that loads with the initial state:

getInitialState: function() { return { panel: "deals", showExtension: false, person: {} }; }, 

And I have this to find a person:

  componentDidMount: function() { this.findPersonFromBackground(); }, findPersonFromBackground: function() { chrome.runtime.sendMessage({ action: "findPerson", email: this.props.currentEmail.from_email }, function(person) { this.setState({person: person}); }.bind(this)); }, 

So everything is working fine. If a person is found, I do one thing, and if not, then another.

When the first one is found, the view switches from an idle state to a real state state quickly, as the API calls are pretty fast.

What is the best way to wait while rendering this first call?

+5
source share
4 answers

One way you can handle it is with an enumeration template. this.state.person code this.state.person either a load dispenser, or a notFound telltale, or an actual person.

 var status = {loading: {}, notFound: {}}; // ... getInitialState: function(){ return {person: status.loading} }, fetchPerson: function(){ doFetchPerson(function(person){ if (person) this.setState({person: person}) else this.setState({person: status.notFound}) }.bind(this)) }, render: function(){ var person = this.state.person) if (person === status.loading) ... else if (person === status.notFound) ... else ... } 
+3
source

There is no good way to do what you ask, which means that the component does not appear at all until any asynchronous operation that the component initiates has completed; the best you can do is use the methods from other answers to this question to do something a little different in case it is not completed.

However, the problem that you are actually trying to solve is to prevent the flash of alternatively displayed content from briefly flashing if the API request is launched and terminates very quickly. If you move the asynchronous operation to the parent component of your component, you can make sure the async operation is complete before you even introduce your child.

If Chrome’s runtime requests are constantly fast, this might be fine, but in general, you should consider what kind of behavior it would take if the async operation takes longer.

+4
source

Is this more of a design issue? You can show the spinner, the empty box, only a preview of the shapes (like the Facebook channel) or nothing at all.

If this is a technical question, return null to render ().

+1
source

Maybe you need this project: https://github.com/toplan/react-hold

You can use a placeholder to save the shape of your component.

+1
source

Source: https://habr.com/ru/post/1203435/


All Articles