Comments (10)
+1
from 3ree.
Yea. It's been on my to-do list and I have free time now so I'll take a look into it shortly.
from 3ree.
Great, thanks @GordyD. I just got it working today, and my server and client code is below. I'm still climbing the learning curve on the tech in this stack so you can probably improve. Plus I've modified some of the original code to play around with it.
// server/app.js
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import thunkMiddleware from 'redux-thunk';
import { createStore, compose, combineReducers, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import * as eventService from './api/service/event';
import * as itemService from './api/service/item';
import myApp from '../universal/reducers';
import routes from '../universal/routes';
import { Router, Route, match, RouterContext } from 'react-router';
import { routeReducer, syncHistory } from 'react-router-redux'
import createMemoryHistory from 'history/lib/createMemoryHistory';
import Promise from 'bluebird';
export function handleRender(req, res) {
Promise.join(
itemService.getItems(),
eventService.getEvents(),
function (initialItems, initialEvents) {
var initialState = {
myApp: {
userId: 'baseUser',
events: initialEvents,
items: initialItems
}
};
const reducer = combineReducers({
routing: routeReducer,
myApp
});
const history = createMemoryHistory();
const historyMiddleware = syncHistory(history);
// Create a new Redux store instance
const store = compose(
applyMiddleware(thunkMiddleware),
applyMiddleware(historyMiddleware),
)(createStore)(reducer, initialState);
// Wire up routing based upon routes
store.dispatch(match(
{ routes: routes, location: req.originalUrl, history: history },
(error, redirectLocation, renderProps) => {
if (error) {
console.log('Error', error);
res.status(400);
res.send(error);
return;
}
if (redirectLocation) {
res.redirect(redirectLocation);
return;
}
// Render the component to a string
const html = ReactDOMServer.renderToString(
<div>
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
</div>
);
// Send the rendered page back to the client with the initial state
res.render('index', { html: html, initialState: JSON.stringify(store.getState()) });
}));
}
);
}
// client/app.js
import ReactDOM from 'react-dom';
import React from 'react';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import { Provider } from 'react-redux';
import { Router, Route, browserHistory } from 'react-router';
import { syncHistory, routeReducer } from 'react-router-redux'
import { getOrSetUserId } from './UserId';
import { setupRealtime } from './Realtime';
import DevTools from '../universal/containers/DevTools';
import routes from '../universal/routes';
import myApp from '../universal/reducers';
import * as actions from '../universal/actions/PulseActions';
import '../style/pure.css';
import '../style/main.css';
import '../style/spinner.css';
// Grab the state from a global injected into server-generated HTML
let initialState = window.__INITIAL_STATE__;
const loggerMiddleware = createLogger({
level: 'info',
collapsed: true,
});
const reducer = combineReducers({
routing: routeReducer,
myApp
});
const reduxRouterMiddleware = syncHistory(browserHistory);
// Create a new Redux store instance
const store = compose(
applyMiddleware(thunkMiddleware, loggerMiddleware),
applyMiddleware(reduxRouterMiddleware),
DevTools.instrument()
)(createStore)(reducer, initialState);
ReactDOM.render(
<div>
<Provider store={store}>
<Router history={browserHistory}>
{routes}
</Router>
</Provider>
</div>,
document.getElementById('app')
);
// Now that we have rendered...
setupRealtime(store, actions);
// lets mutate state and set UserID as key from local storage
store.dispatch(actions.setUserId(getOrSetUserId()));
from 3ree.
Oh nice. I've just created a PR here with the changes that follow a similar approach in addition to some other simplifications to improve readability of code and conform to redux standard approaches.
from 3ree.
I also added in DevTools too ;)
from 3ree.
Sounds great, I do have an error related to DevTools in that code FYI, but it seems benign.
Glad you're able to spend time on this project; I can see 3ree as my choice stack going forward.
Side note, I wish there was an easy way to merge in your changes to my own project. Easy, as in updating an npm package easy :). Prob means building a framework around it in some fashion.
from 3ree.
It's been merged in.
What is the error?
As for an easy way to merge in or update your codebase with 3ree - that is certainly food for thought. I'll think about potential paths for this to be possible.
Thanks your support on this task!
from 3ree.
@GordyD @snobear I was able to run this PR (Prior to Merge) and no errors related to DevTools and all worked as expected. @GordyD thank you for jumping in on this so fast!
from 3ree.
Sorry, to clarify on my comment:
Sounds great, I do have an error related to DevTools in that code FYI, but it seems benign.
I was referring to the code I had posted, and not your PR at the time.
from 3ree.
@snobear I do see a benign error related to DevTools now that I inspected after running npm start and posted it in the issues... do you see the same thing?
from 3ree.
Related Issues (20)
- Is Jade Necessary? HOT 4
- Sorry there is no Error
- Required prop `location` HOT 1
- Add Unit Tests HOT 1
- Add ESlint HOT 4
- not updating between multiple browsers HOT 1
- Upgrade to Babel 6 HOT 3
- Having a grandparent directory named 'src' causes bug HOT 2
- Error on npm start HOT 11
- NOT an Issue - More a Question - Account Integration HOT 7
- rethinkdb not installed as global
- Misc HOT 3
- Unhandled rejection TypeError when loading page HOT 11
- Error running project on Windows HOT 3
- Slow loading on demo app HOT 3
- Warning: React attempted to reuse markup in a container but the checksum was invalid HOT 3
- Any plans to add auth? HOT 4
- Why not add PostCSS and Autoprefixer?
- Can't Install on Ubuntu 16.04.1 HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from 3ree.