Fuad Ibrahimov
Fuad Ibrahimov

Reputation: 512

Server side data fetch with react-router

I am rendering my React-router on server in my express app. here is my code

app.use((req, res) => {

match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
console.log(renderProps)
if (error) {
  res.status(500).send(error.message)
} else if (redirectLocation) {
  res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
  let component = renderToString(<RoutingContext {...renderProps}/>);

  var html = renderToStaticMarkup(body(null,
      div({id: 'content', dangerouslySetInnerHTML: {__html:component}}),
      script({src: '/js/main.js'})
  ))
  res.end(html)
    } else {
      res.status(404).send('Not found')
    }
  })
});

and it works.I can route without refresh. but how i can refer to my express routes to make a queries to my database before my component will be rendered (not ajax queries)..

Upvotes: 0

Views: 528

Answers (1)

Joe Haddad
Joe Haddad

Reputation: 1740

You can query your database and use a callback which captures the variables you need to respond to the web request, e.g. res. Alternatively, you can use generators to yield the result from your database. Your solution will really matter on what database and library you're using.

Here's an example:

const mysql = require('mysql');
let connection = mysql.createConnection({ ... });

// ...

app.use((req, res) => {
  match({ routes, location: req.url}, (error, redirectLocation, renderProps) => {
    if (error) res.status(500).send(error.message);
    else if (redirectLocation) res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    else if (renderProps) {
      connection.query('SELECT 2 + 2 AS sample', (err, rows, fields) => {
        if (err) res.status(500).send(err);
        else {
          let fromDatabase = rows[0].sample;
          let component = renderToString(<RoutingContext {...renderProps} />);
          let html = renderToStaticMarkup(body(
            null,
            div({ id: 'content', dangerouslySetInnerHTML: { __html: component } }),
            script({ src: '/js/main.js' })
          ));
          res.end(html);
        }
      });
    } else {
      res.status(404).send('Not found');
    }
  });
});

// ...

Upvotes: 1

Related Questions