Unverified Commit 5a5e6004 authored by TodorTotev's avatar TodorTotev Committed by GitHub

Refactor with redux persist example (#13338)

Related to [11014](https://github.com/zeit/next.js/issues/11014)

First and most important, removed the getInitialProps and used getStaticProps.

Then, I refactored Counter, DataList and Examples components.
I have refactored them from class-based components to functional. Also in each component the redux implementation was refactored using the new hooks API, which resulted in ~40% less code.

If you want me to change anything or you are not satisfied with any given change, I'm open to suggestions.
parent 73c8b8ca
import { Component } from 'react' import { useSelector, useDispatch } from 'react-redux'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { incrementCount, decrementCount, resetCount } from '../store' import { incrementCount, decrementCount, resetCount } from '../store'
class Counter extends Component { const Counter = () => {
increment = () => { const counter = useSelector((state) => state.count)
const { incrementCount } = this.props const dispatch = useDispatch()
incrementCount()
}
decrement = () => { return (
const { decrementCount } = this.props <div>
decrementCount() <h1>
} Count: <span>{counter}</span>
</h1>
reset = () => { <button onClick={() => dispatch(incrementCount())}>+1</button>
const { resetCount } = this.props <button onClick={() => dispatch(decrementCount())}>-1</button>
resetCount() <button onClick={() => dispatch(resetCount())}>Reset</button>
} </div>
)
render() {
const { count } = this.props
return (
<div>
<h1>
Count: <span>{count}</span>
</h1>
<button onClick={this.increment}>+1</button>
<button onClick={this.decrement}>-1</button>
<button onClick={this.reset}>Reset</button>
</div>
)
}
}
function mapStateToProps(state) {
const { count } = state
return { count }
} }
const mapDispatchToProps = (dispatch) =>
bindActionCreators({ incrementCount, decrementCount, resetCount }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(Counter) export default Counter
import { Component } from 'react' import { useState } from 'react'
import { connect } from 'react-redux' import { useSelector, useDispatch } from 'react-redux'
import { bindActionCreators } from 'redux'
import { loadExampleData, loadingExampleDataFailure } from '../store' import { loadExampleData, loadingExampleDataFailure } from '../store'
import { useEffect } from 'react'
class DataList extends Component { const DataList = () => {
state = { const dispatch = useDispatch()
isDataLoading: false, const exampleData = useSelector((state) => state.exampleData)
} const error = useSelector((state) => state.error)
const [isLoading, setIsLoading] = useState(false)
componentDidMount() { useEffect(() => {
const { loadExampleData, loadingExampleDataFailure } = this.props setIsLoading(true)
const self = this
this.setState({ isDataLoading: true })
window window
.fetch('https://jsonplaceholder.typicode.com/users') .fetch('https://jsonplaceholder.typicode.com/users')
.then(function (response) { .then((response) => {
if (response.status !== 200) { if (response.status !== 200) {
console.log( console.log(
'Looks like there was a problem. Status Code: ' + response.status 'Looks like there was a problem. Status Code: ' + response.status
) )
loadingExampleDataFailure() dispatch(loadingExampleDataFailure())
self.setState({ isDataLoading: false }) setIsLoading(false)
return return
} }
response.json().then(function (data) { response.json().then((data) => {
loadExampleData(data) dispatch(loadExampleData(data))
self.setState({ isDataLoading: false }) setIsLoading(false)
}) })
}) })
.catch(function (err) { .catch((err) => {
console.log('Fetch Error :-S', err) console.log('Fetch Error :-S', err)
loadingExampleDataFailure() dispatch(loadingExampleDataFailure())
self.setState({ isDataLoading: false }) setIsLoading(false)
}) })
} }, [dispatch])
render() { return (
const { exampleData, error } = this.props <div>
const { isDataLoading } = this.state <h1>API DATA:</h1>
{exampleData && !isLoading ? (
return ( <pre>
<div> <code>{JSON.stringify(exampleData, null, 2)}</code>
<h1>API DATA:</h1> </pre>
{exampleData && !isDataLoading ? ( ) : (
<pre> <p style={{ color: 'blue' }}>Loading...</p>
<code>{JSON.stringify(exampleData, null, 2)}</code> )}
</pre> {error && <p style={{ color: 'red' }}>Error fetching data.</p>}
) : ( </div>
<p style={{ color: 'blue' }}>Loading...</p> )
)}
{error && <p style={{ color: 'red' }}>Error fetching data.</p>}
</div>
)
}
}
function mapStateToProps(state) {
const { exampleData, error } = state
return { exampleData, error }
} }
const mapDispatchToProps = (dispatch) =>
bindActionCreators({ loadExampleData, loadingExampleDataFailure }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(DataList) export default DataList
import { connect } from 'react-redux' import { useSelector } from 'react-redux'
import Clock from './clock' import Clock from './clock'
import Counter from './counter' import Counter from './counter'
import DataList from './data-list' import DataList from './data-list'
function Examples({ lastUpdate, light }) { const Examples = () => {
const lastUpdate = useSelector((state) => state.lastUpdate)
const light = useSelector((state) => state.light)
return ( return (
<div> <div>
<Clock lastUpdate={lastUpdate} light={light} /> <Clock lastUpdate={lastUpdate} light={light} />
...@@ -13,9 +15,4 @@ function Examples({ lastUpdate, light }) { ...@@ -13,9 +15,4 @@ function Examples({ lastUpdate, light }) {
) )
} }
function mapStateToProps(state) { export default Examples
const { lastUpdate, light } = state
return { lastUpdate, light }
}
export default connect(mapStateToProps)(Examples)
...@@ -10,10 +10,10 @@ ...@@ -10,10 +10,10 @@
"next": "latest", "next": "latest",
"react": "^16.7.0", "react": "^16.7.0",
"react-dom": "^16.7.0", "react-dom": "^16.7.0",
"react-redux": "^5.0.1", "react-redux": "7.2.0",
"redux": "^3.6.0", "redux": "4.0.5",
"redux-devtools-extension": "^2.13.2", "redux-devtools-extension": "^2.13.2",
"redux-persist": "^5.10.0" "redux-persist": "6.0.0"
}, },
"license": "ISC" "license": "ISC"
} }
import { Component } from 'react' import { useEffect } from 'react'
import { connect } from 'react-redux' import { useDispatch } from 'react-redux'
import { startClock, serverRenderClock } from '../store' import { startClock, serverRenderClock, initializeStore } from '../store'
import Examples from '../components/examples' import Examples from '../components/examples'
class Index extends Component { const Index = () => {
static getInitialProps({ reduxStore, req }) { const dispatch = useDispatch()
const isServer = !!req useEffect(() => {
// DISPATCH ACTIONS HERE ONLY WITH `reduxStore.dispatch` setInterval(() => dispatch(startClock(), 1000))
reduxStore.dispatch(serverRenderClock(isServer)) }, [dispatch])
return {} return <Examples />
} }
componentDidMount() {
// DISPATCH ACTIONS HERE FROM `mapDispatchToProps`
// TO TICK THE CLOCK
this.timer = setInterval(() => this.props.startClock(), 1000)
}
componentWillUnmount() { export async function getStaticProps() {
clearInterval(this.timer) const store = initializeStore()
} store.dispatch(serverRenderClock())
render() { return {
return <Examples /> props: {},
} }
} }
const mapDispatchToProps = { startClock }
export default connect(null, mapDispatchToProps)(Index) export default Index
...@@ -90,9 +90,11 @@ const persistConfig = { ...@@ -90,9 +90,11 @@ const persistConfig = {
const persistedReducer = persistReducer(persistConfig, reducer) const persistedReducer = persistReducer(persistConfig, reducer)
export function initializeStore(initialState = exampleInitialState) { export function initializeStore(initialState = exampleInitialState) {
return createStore( const store = createStore(
persistedReducer, persistedReducer,
initialState, initialState,
composeWithDevTools(applyMiddleware()) composeWithDevTools(applyMiddleware())
) )
return store
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment