airbnb / hypernova

A service for server-side rendering your JavaScript views
MIT License
5.82k stars 208 forks source link

Hypernova ignoring props sometimes #86

Closed dpuscher closed 7 years ago

dpuscher commented 7 years ago

I am sorry if the description of my issue is a big vague, but I am not really sure where to start when fixing that error. I am testing hypernova with hypernova-ruby in a Rails 4.2 environment. Server-side rendering works very well most of the time. But sometimes it seems like there are no props passed to the component for rendering (in hypernova). I already checked the context (in getComponent function) and the props are passed to the server, anyhow the resulting string is build with the default props.

Any idea where to start on this?

ljharb commented 7 years ago

What's your top-level component look like?

dpuscher commented 7 years ago

My top level component isn't special. I will try to implement a minimum-example which shows the problem. 😊

dpuscher commented 7 years ago

Okay, I figured out what my problem was: I am loading my javascript asynchronously in the head. So the javascript got executed before the dom was ready. This lead to the situation that the renderReactmethod got called when the placeholder-div was present but the script-tag containing the data was not. Also some components which appeared later in the dom were not initialized.

I am using the following code to make sure the dom is ready before initializing the components:

const renderReactComponents = () => {
  renderReact("Foo", Foo);
};

const domLoaded = () => {
  document.removeEventListener("DOMContentLoaded", domLoaded);
  window.removeEventListener("load", domLoaded);
  renderReactComponents();
};

if (typeof document !== "undefined" && document.readyState !== "loading") {
  renderReactComponents();
} else {
  document.addEventListener("DOMContentLoaded", domLoaded);
  window.addEventListener("load", domLoaded);
}