One of the biggest advantages of React.js is supposed to be server-side rendering. The problem is that the key function React.renderC
Wanna share with you my approach of server side rendering using Flux, little be simplified for example:
Let's say we have component with initial data from store:
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: myStore.getData()
};
}
}
If class require some preloaded data for initial state let's create Loader for MyComponent:
class MyComponentLoader {
constructor() {
myStore.addChangeListener(this.onFetch);
}
load() {
return new Promise((resolve, reject) => {
this.resolve = resolve;
myActions.getInitialData();
});
}
onFetch = () => this.resolve(data);
}
Store:
class MyStore extends StoreBase {
constructor() {
switch(action => {
case 'GET_INITIAL_DATA':
this.yourFetchFunction()
.then(response => {
this.data = response;
this.emitChange();
});
break;
}
getData = () => this.data;
}
Now just load data in router:
on('/my-route', async () => {
await new MyComponentLoader().load();
return ;
});