Is there any way of using fetch on the server for isomorphic rendering?
See original GitHub issueSteps to reproduce
Require isomorphic-fetch or node-fetch on server_rendering.js
Expected behavior
Fetch should work, and it should finish the request (and callback) before generating the html for the browser.
Actual behavior
I’m requiring node-fetch with const fetch = require('node-fetch');
. Using it results in
<ExecJS::ProgramError: ReferenceError: fetch is not defined>
.
If, instead, I do const fetch = require('isomorphic-fetch');
I get
Unhandled promise rejection (rejection id: 2): ReferenceError: XMLHttpRequest is not defined
.
System configuration
Sprockets or Webpacker version: 3.0.2 React-Rails version: 2.4.2 Rect_UJS version: 2.4.2 Rails version: 5.1.4 Ruby version: 2.4.1
How can I solve this? I want a product list in an app to be filled with data from an API, this currently works on client-rendering, doing a fetch call in componentWillMount and calling this.setState with the response (while showing a loading screen meanwhile).
But for server-side rendering I need the data to be inserted when the server compiles it. I don’t know how to make it work. Maybe I could:
- Make my products component stateless, with the product list as props.
- Implement a custom renderer which does the api call and load the response as props in an App component.
- Make a wrapper component for the product list which only tries to fetch the data if the props from the app are empty.
The problem is I’d still have to do the requests in Ruby, and it seems awfully complex for something I could solve just using fetch on the server. Would the solution above work? Is there any easier solution?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:10 (3 by maintainers)
Have a look at http://ruby-hyperloop.org (the hyper-react gem). Look at isomorphic helpers module for how to get this to work…
catmando This one? https://github.com/ruby-hyperloop/hyper-react/blob/master/lib/reactive-ruby/isomorphic_helpers.rb
I haven’t seen anything applicable there. JS server-side fetch is really necessary - to optimize the Rails data loading on SSR. Currently I have to pre-load everything via props - whereas I would prefer to load it dynamically in portions.