simple server/client routing react-express(nodejs)

491 Views Asked by At

App.js has a link to - I am not understanding if I need action creators/reducers? if so how to wire it up with server side rendering?

Basically on load of otherComponent - should make an API call from server.js by path and inject response back to the component - where does react actions fit in this picture?

server.js:

app.get('/test', (req, res) => {
    res.send(<otherComponent />); -> this is returning json right now? How to handle this path for example here - where this should make an api call.
});

app.get('*', (req, res) => {
  res.send(`
            <!doctype html>
            <html>
                <head>
                    <title>My website</title>
                    <meta name="viewport" content="width=device-width, initial-scale=1">
            </head>
                <body>
                    <div id='app'>${renderToString(
                        <Provider store={createStore(reducers)}>
                            <StaticRouter location={req.url} context={{}}>
                                <App />
                            </StaticRouter>
                        </Provider>
                    )}</div>
                    <script src='bundle.js'></script>

                </body>
            </html>
        `);
});
3

There are 3 best solutions below

0
On

In your React component, just fire the API calls you need

componentDidMount() {
    $.get('/test', data => {
        // use data
    });
} 

Typically with an SPA, you'd serve the full client app from the server on the first request, use client-side routing for your views and then fire any API requests (like the example).

6
On

Update: I think you may find this tutorial helpful: https://medium.com/@foxhound87/server-side-rendering-with-react-router-we-must-react-ep-04-ad03b6b9e05d


Use create-react-app to create your app. Do yarn add react-router-dom to add React's router. More info on this here: https://reacttraining.com/react-router/web/guides/quick-start.

  1. Put <Router /> around the App JSX.
  2. Use the <Link /> to create links to <Route />. When the path in Link matches, the correct Route renders.
  3. Note also the requests in componentDidMount.

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <div className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h2>Welcome to React</h2>
          </div>
          <nav>
            <Link to="/">Home</Link>
            <Link to="/test">Test</Link>
          </nav>
          <Route path="/" exact component={Index} />
          <Route path="/test" exact component={Test} />
        </div>
      </Router>
    );
  }
}

class Index extends Component {
  onComponentDidMount() {
    fetch('http://yourapi.com')
      .then(data => this.setState(data));
  }
  render() {
    return (
      <div>
        <h1>Index Component</h1>
        <div>{ /* do something with this.state.data */}</div>
      </div>
    );
  }
}

class Test extends Component {
  onComponentDidMount() {
    fetch('http://yourapi.com')
      .then(data => this.setState(data));
  }
  render() {
    return (
      <div>
        <h1>Test Component</h1>
        <div>{ /* do something with this.state.data */}</div>
      </div>
    );
  }
}

export default App;
0
On

In the definition of <otherComponent \>, fetch the data in componentDidMount(), then do store.dispatch({ type: 'RECEIVED_DATA', data }) to update the store.