redux-saga HOC for Next.js
yarn add next-redux-saga
next-redux-saga
uses the redux store created by next-redux-wrapper. Please refer to their documentation for more information.
The working example below is based off pages/index.js.
Try it out:
- Clone this repository
- Install dependencies:
yarn
- Start the project:
yarn start
- Visit http://localhost:3000
root-reducer.js
function rootReducer(state = {}, action) {
switch (action.type) {
case 'GET_REDUX_PROP':
return {...state, redux: action.data}
case 'GET_REDUX_SAGA_PROP_SUCCESS':
return {...state, reduxSaga: action.data}
default:
return state
}
}
root-saga.js
import {delay} from 'redux-saga'
import {all, call, put, takeEvery} from 'redux-saga/effects'
function helloSaga() {
console.log('Hello Saga!')
}
function* getReduxSagaPropSaga() {
yield call(delay, 500)
yield put({
type: 'GET_REDUX_SAGA_PROP_SUCCESS',
data: 'Hello redux-saga!'
})
}
function* rootSaga() {
yield all([
call(helloSaga),
takeEvery('GET_REDUX_SAGA_PROP', getReduxSagaPropSaga)
])
}
configure-store.js
import createSagaMiddleware from 'redux-saga'
import {createStore, applyMiddleware} from 'redux'
import rootReducer from './root-reducer'
import rootSaga from './root-saga'
const sagaMiddleware = createSagaMiddleware()
function configureStore(initialState) {
const store = createStore(
rootReducer,
initialState,
applyMiddleware(sagaMiddleware)
)
// NOTE: you must attach `sagaTask` to the store
store.sagaTask = sagaMiddleware.run(rootSaga)
return store
}
example-page.js
import React, {Component} from 'react'
import {string} from 'prop-types'
import withRedux from 'next-redux-wrapper'
import withReduxSaga from 'next-redux-saga'
class ExamplePage extends Component {
static propTypes = {
static: string,
redux: string,
reduxSaga: string
}
static async getInitialProps({store}) {
store.dispatch({type: 'GET_REDUX_PROP', data: 'Hello redux!'})
store.dispatch({type: 'GET_REDUX_SAGA_PROP'})
return {static: 'Hello static!'}
}
render() {
return (
<ul>
<li>prop from getInitialProps: {this.props.static}</li>
<li>prop from redux: {this.props.redux}</li>
<li>prop from redux-saga: {this.props.reduxSaga}</li>
</ul>
)
}
}
export default withRedux(configureStore, state => state)(
withReduxSaga(ExamplePage)
)
Thanks goes to these wonderful people (emoji key):
Brent Mealhouse 💻 📖 |
---|
This project follows the all-contributors specification. Contributions of any kind welcome!
- Fork this repository to your own GitHub account and then clone it to your local device
- Install the dependecies:
yarn
- Link the package to the global module directory:
yarn link
- Run
yarn test -- --watch
and start making your changes - You can use
yarn link next-redux-saga
to test your changes in an actual project
MIT