I have a React app and here is my server code:
app.get('*', (req, res) => {
let history = createMemoryHistory();
let store = configureStore();
let routes = createRoutes(history);
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (redirectLocation) {
res.redirect(301, redirectLocation.pathname + redirectLocation.search);
} else if (error) {
res.status(500).send(error.message);
} else if (renderProps == null) {
res.status(404).send('Not found');
} else {
let { query, params } = renderProps;
let comp = renderProps.components[renderProps.components.length - 1];
console.log('fetching');
comp.fetchData({ store, params })
.then(() => {
console.log('done fetching');
let html = ReactDOMServer.renderToString(
<Provider store={store}>
{ <RouterContext {...renderProps}/> }
</Provider>
);
const template = store.getState().template;
const og = templateToOpenGraph(template);
const full = wrap(html, store.getState(), og);
res.set({ 'Cache-Control': 'public, max-age=300' })
res.send(full);
})
}
});
})
When I start the server, it starts up just fine. But when I hit a route (any route), I get an error:
TypeError: comp.fetchData is not a function
What do I need to do? I'm not the greatest with react, so if I'm missing something obvious, please do let me know.
Thanks!
There should be method fetchData
in your component.
I don't have your routes config but for example you have something like this in your routes.js
file
<Route path="/" component={Root}>
<Route path="view/:id" component={View} />
...
</Route>
When you load page http://example.com/view/1231
in your browser, component View
will be rendered. You should implement method fetchData
. This method will be called before rendering View
class View extends React.Component {
fetchData() {
// implement fetch data here
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With