Search code examples
javascriptreactjsreduxreactjs-fluxisomorphic-javascript

isomorphic react.js without flux


I am newbie with react.js . I want to make isomorphic react.js component . I wonder is it possible to make it without flux pattern ? Now I have little component and there is api fetch method inside component and as it seems this api call runs twice :( .

For more clarity, I want to render DOM in server side , and want to handle react.js component events in browser side .

My component looks like :

Class MyComponent extends React.Component{

 // my component code 
 // components events 

 render() {} 

}


if (!is_server()) {


apiFetch.my_api_call(function (result) {
    ReactDom.render(<MyComponent data={result.data}/>, document.getElementById('navigation'))
});


}else{

apiFetch.my_api_call(function (result) {
    res.status(200).send(
        ReactDOMServer.renderToString(React.createElement(MyComponent, {data: result.data}))
    );
});

Solution

  • Make a parent Component whose child will be MyComponent

    class ParentComponent extends React.Component {
      componentDidMount() {
        // make api call
        apiCall.then((data) => {
          this.setState({
            reqData : data,
          })
        })
      }
    
      getComponentToRender() {
        if(typeof this.state.reqData === 'undefined') {
          return false;
        } else {
          return (
            <MyComponent data={result.data}/>
          )
        }
      }
    
      render() {
        const componentToRender = this.getComponentToRender();
        return (
          <div>
            <componentToRender />
          </div>
        )
      }
    }
    

    Now, render your ParentComponent irrespective of the api call. Once, the ParentComponent is mounted, it will automatically trigger the rendering of MyComponent.