Skip to content

Commit

Permalink
enhance-with-redux-saga (vercel#13764)
Browse files Browse the repository at this point in the history
[11014](vercel#11014)

Removed getInitialProps from _app
  • Loading branch information
todortotev authored and rokinsky committed Jul 11, 2020
1 parent a6bbd2d commit bd13f43
Show file tree
Hide file tree
Showing 8 changed files with 19 additions and 104 deletions.
59 changes: 2 additions & 57 deletions examples/with-redux-saga/README.md
Expand Up @@ -53,65 +53,10 @@ Our page is located at `pages/index.js` so it will map the route `/`. To get the

For safety it is recommended to wrap all pages, no matter if they use Redux or not, so that you should not care about it anymore in all child components.

`withRedux` function accepts `makeStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `makeStore` function will receive initialState as one argument and should return a new instance of redux store each time when called, no memoization needed here. See the [full example](https://github.com/kirill-konshin/next-redux-wrapper#usage) in the Next Redux Wrapper repository. And there's another package [next-connect-redux](https://github.com/huzidaha/next-connect-redux) available with similar features.
`withRedux` function accepts `makeStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `makeStore` should return a new instance of redux store each time when called, no memoization needed here. See the [full example](https://github.com/kirill-konshin/next-redux-wrapper#usage) in the Next Redux Wrapper repository.

To pass the initial state from the server to the client we pass it as a prop called `initialState` so then it's available when the client takes over.

The trick here for supporting universal redux is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish in `store.js`
The trick here for supporting universal redux is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store and hydrate it when needed. That's what we accomplish in `store.js`

The clock, under `components/clock.js`, has access to the state using the `connect` function from `react-redux`. In this case Clock is a direct child from the page but it could be deep down the render tree.

The second example, under `components/counter.js`, shows a simple add counter function with a class component implementing a common redux pattern of mapping state and props. Again, the first render is happening in the server and instead of starting the count at 0, it will dispatch an action in redux that starts the count at 1. This continues to highlight how each navigation triggers a server render first and then a client render second, when you navigate between pages.

## What changed with next-redux-saga

The digital clock is updated every second using the `runClockSaga` found in `saga.js`.

All pages are also being wrapped by `next-redux-saga` using a helper function from `store.js`:

```js
import withRedux from 'next-redux-wrapper'
import nextReduxSaga from 'next-redux-saga'
import configureStore from './store'

export function withReduxSaga(BaseComponent) {
return withRedux(configureStore)(nextReduxSaga(BaseComponent))
}

/**
* Usage:
*
* class Page extends Component {
* // implementation
* }
*
* export default withReduxSaga(Page)
*/
```

If you need to pass `react-redux` connect args to your page, you could use the following helper instead:

```js
import withRedux from 'next-redux-wrapper'
import nextReduxSaga from 'next-redux-saga'
import configureStore from './store'

export function withReduxSaga(...connectArgs) {
return (BaseComponent) =>
withRedux(configureStore, ...connectArgs)(nextReduxSaga(BaseComponent))
}

/**
* Usage:
*
* class Page extends Component {
* // implementation
* }
*
* export default withReduxSaga(state => state)(Page)
*/
```

Since `redux-saga` is like a separate thread in your application, we need to tell the server to END the running saga when all asynchronous actions are complete. This is automatically handled for you by wrapping your components in `next-redux-saga`. To illustrate this, `pages/index.js` loads placeholder JSON data on the server from [https://jsonplaceholder.typicode.com/users](https://jsonplaceholder.typicode.com/users). If you refresh `pages/other.js`, the placeholder JSON data will **NOT** be loaded on the server, however, the saga is running on the client. When you click _Navigate_, you will be taken to `pages/index.js` and the placeholder JSON data will be fetched from the client. The placeholder JSON data will only be fetched **once** from the client or the server.

After introducing `redux-saga` there was too much code in `store.js`. For simplicity and readability, the actions, reducers, sagas, and store creators have been split into seperate files: `actions.js`, `reducer.js`, `saga.js`, `store.js`
5 changes: 2 additions & 3 deletions examples/with-redux-saga/package.json
Expand Up @@ -8,16 +8,15 @@
"start": "next start"
},
"dependencies": {
"es6-promise": "4.1.1",
"next": "latest",
"next-redux-wrapper": "6.0.0",
"next-redux-wrapper": "^6.0.2",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-redux": "7.2.0",
"redux": "4.0.5",
"redux-saga": "1.1.3"
},
"devDependencies": {
"redux-devtools-extension": "2.13.2"
"redux-devtools-extension": "^2.13.8"
}
}
26 changes: 3 additions & 23 deletions examples/with-redux-saga/pages/_app.js
@@ -1,27 +1,7 @@
import App from 'next/app'
import { END } from 'redux-saga'
import { wrapper } from '../store'

class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
const pageProps = {
...(Component.getInitialProps
? await Component.getInitialProps(ctx)
: {}),
}

if (ctx.req) {
ctx.store.dispatch(END)
await ctx.store.sagaTask.toPromise()
}

return { pageProps }
}

render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
function App({ Component, pageProps }) {
return <Component {...pageProps} />
}

export default wrapper.withRedux(MyApp)
export default wrapper.withRedux(App)
8 changes: 3 additions & 5 deletions examples/with-redux-saga/pages/index.js
Expand Up @@ -11,11 +11,8 @@ const Index = () => {
useEffect(() => {
dispatch(startClock())
}, [dispatch])
return (
<>
<Page title="Index Page" linkTo="/other" NavigateTo="Other Page" />
</>
)

return <Page title="Index Page" linkTo="/other" NavigateTo="Other Page" />
}

export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
Expand All @@ -25,6 +22,7 @@ export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
store.dispatch(loadData())
store.dispatch(END)
}

await store.sagaTask.toPromise()
})

Expand Down
1 change: 1 addition & 0 deletions examples/with-redux-saga/pages/other.js
Expand Up @@ -6,6 +6,7 @@ import Page from '../components/page'

const Other = () => {
const dispatch = useDispatch()

useEffect(() => {
dispatch(startClock())
}, [dispatch])
Expand Down
9 changes: 5 additions & 4 deletions examples/with-redux-saga/reducer.js
@@ -1,16 +1,17 @@
import { actionTypes } from './actions'
import { HYDRATE } from 'next-redux-wrapper'

export const exampleInitialState = {
const initialState = {
count: 0,
error: false,
lastUpdate: 0,
light: false,
placeholderData: null,
}

function reducer(state = exampleInitialState, action) {
function reducer(state, action) {
switch (action.type) {
case '__NEXT_REDUX_WRAPPER_HYDRATE__': {
case HYDRATE: {
return { ...state, ...action.payload }
}

Expand All @@ -35,7 +36,7 @@ function reducer(state = exampleInitialState, action) {
case actionTypes.RESET:
return {
...state,
...{ count: exampleInitialState.count },
...{ count: initialState.count },
}

case actionTypes.LOAD_DATA_SUCCESS:
Expand Down
4 changes: 0 additions & 4 deletions examples/with-redux-saga/saga.js
@@ -1,10 +1,6 @@
import { all, call, delay, put, take, takeLatest } from 'redux-saga/effects'
import es6promise from 'es6-promise'

import { actionTypes, failure, loadDataSuccess, tickClock } from './actions'

es6promise.polyfill()

function* runClockSaga() {
yield take(actionTypes.START_CLOCK)
while (true) {
Expand Down
11 changes: 3 additions & 8 deletions examples/with-redux-saga/store.js
Expand Up @@ -2,7 +2,7 @@ import { applyMiddleware, createStore } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { createWrapper } from 'next-redux-wrapper'

import rootReducer, { exampleInitialState } from './reducer'
import rootReducer from './reducer'
import rootSaga from './saga'

const bindMiddleware = (middleware) => {
Expand All @@ -13,14 +13,9 @@ const bindMiddleware = (middleware) => {
return applyMiddleware(...middleware)
}

export const makeStore = (context, initialState = exampleInitialState) => {
export const makeStore = (context) => {
const sagaMiddleware = createSagaMiddleware()

const store = createStore(
rootReducer,
initialState,
bindMiddleware([sagaMiddleware])
)
const store = createStore(rootReducer, bindMiddleware([sagaMiddleware]))

store.sagaTask = sagaMiddleware.run(rootSaga)

Expand Down

0 comments on commit bd13f43

Please sign in to comment.