Giter Site home page Giter Site logo

Move to react-router-redux about 3ree HOT 10 CLOSED

gordyd avatar gordyd commented on May 2, 2024
Move to react-router-redux

from 3ree.

Comments (10)

tzarger avatar tzarger commented on May 2, 2024

+1

from 3ree.

GordyD avatar GordyD commented on May 2, 2024

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.

snobear avatar snobear commented on May 2, 2024

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.

GordyD avatar GordyD commented on May 2, 2024

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.

GordyD avatar GordyD commented on May 2, 2024

I also added in DevTools too ;)

from 3ree.

snobear avatar snobear commented on May 2, 2024

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.

GordyD avatar GordyD commented on May 2, 2024

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.

tzarger avatar tzarger commented on May 2, 2024

@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.

snobear avatar snobear commented on May 2, 2024

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.

tzarger avatar tzarger commented on May 2, 2024

@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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.