Unverified Commit 11597655 authored by Todor Totev's avatar Todor Totev Committed by GitHub

Enhance with redux thunk example (#13576)

* Refactored the store so that it doesnt use getInitialProps

* Applied the changes in the _app file

* Refactored the wrapper so that it uses the new store flow

* Removed the old redux syntax

Instead of passing the state from the parent component, I have used the new redux hooks to retrieve the current state.

* The clock no longer requires state to be passed too

* Updated the variable names

* forgot to bring back hot reloading

* Applied requested change.
parent a32fa424
const pad = (n) => (n < 10 ? `0${n}` : n)
import { useSelector } from 'react-redux'
const format = (t) =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const formatTime = (time) => {
return new Date(time).toJSON().slice(11, 19)
}
const Clock = ({ lastUpdate, light }) => (
<div className={light ? 'light' : ''}>
{format(new Date(lastUpdate))}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82fa58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
const Clock = () => {
const lastUpdate = useSelector((state) => state.timer.lastUpdate)
const light = useSelector((state) => state.timer.light)
return (
<div className={light ? 'light' : ''}>
{formatTime(lastUpdate)}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82fa58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
)
.light {
background-color: #999;
}
`}</style>
</div>
)
}
export default Clock
import { useSelector } from 'react-redux'
import Clock from './clock'
import Counter from './counter'
const Examples = () => {
const lastUpdate = useSelector((state) => state.timer.lastUpdate)
const light = useSelector((state) => state.timer.light)
return (
<div style={{ marginBottom: 10 }}>
<Clock lastUpdate={lastUpdate} light={light} />
<Clock />
<Counter />
</div>
)
......
import { Component } from 'react'
import initializeStore from '../store'
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
function getOrCreateStore(initialState) {
// Always make a new store if server, otherwise state is shared between requests
if (typeof window === 'undefined') {
return initializeStore(initialState)
}
// Create store if unavailable on the client and set it on the window object
if (!window[__NEXT_REDUX_STORE__]) {
window[__NEXT_REDUX_STORE__] = initializeStore(initialState)
}
return window[__NEXT_REDUX_STORE__]
}
export default function withReduxStore(App) {
return class AppWithRedux extends Component {
static async getInitialProps(appContext) {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const store = getOrCreateStore()
// Provide the store to getInitialProps of pages
appContext.ctx.store = store
return {
...(App.getInitialProps ? await App.getInitialProps(appContext) : {}),
initialReduxState: store.getState(),
}
}
render() {
const { initialReduxState } = this.props
return <App {...this.props} store={getOrCreateStore(initialReduxState)} />
}
}
}
import { Provider } from 'react-redux'
import App from 'next/app'
import withReduxStore from '../lib/with-redux-store'
import { useStore } from '../store'
class MyApp extends App {
render() {
const { Component, pageProps, store } = this.props
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
}
export default function App({ Component, pageProps }) {
const store = useStore(pageProps.initialReduxState)
export default withReduxStore(MyApp)
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import Link from 'next/link'
import getStore from '../store'
import { startClock, serverRenderClock } from '../actions'
import { startClock } from '../actions'
import Examples from '../components/examples'
const Index = () => {
......@@ -21,13 +20,4 @@ const Index = () => {
)
}
export async function getStaticProps() {
const store = getStore()
store.dispatch(serverRenderClock())
return {
props: {},
}
}
export default Index
import { connect } from 'react-redux'
import { useSelector } from 'react-redux'
import Link from 'next/link'
const codeStyle = {
......@@ -9,17 +9,19 @@ const codeStyle = {
marginBottom: 10,
}
const ShowReduxState = (state) => (
<>
<pre style={codeStyle}>
<code>{JSON.stringify(state, null, 4)}</code>
</pre>
<Link href="/">
<a>Go Back Home</a>
</Link>
</>
)
const ShowReduxState = () => {
const state = useSelector((state) => state)
const mapDispatchToProps = (state) => state
return (
<>
<pre style={codeStyle}>
<code>{JSON.stringify(state, null, 4)}</code>
</pre>
<Link href="/">
<a>Go Back Home</a>
</Link>
</>
)
}
export default connect(mapDispatchToProps)(ShowReduxState)
export default ShowReduxState
import { useMemo } from 'react'
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'
import reducers from './reducers'
// CREATING INITIAL STORE
export default function getStore(initialState) {
const store = createStore(
let store
function initStore(initialState) {
return createStore(
reducers,
initialState,
composeWithDevTools(applyMiddleware(thunkMiddleware))
)
}
// IF REDUCERS WERE CHANGED, RELOAD WITH INITIAL STATE
if (module.hot) {
module.hot.accept('./reducers', () => {
const createNextReducer = require('./reducers').default
export const initializeStore = (preloadedState) => {
let _store = store ?? initStore(preloadedState)
store.replaceReducer(createNextReducer(initialState))
// After navigating to a page with an initial Redux state, merge that state
// with the current state in the store, and create a new store
if (preloadedState && store) {
_store = initStore({
...store.getState(),
...preloadedState,
})
// Reset the current store
store = undefined
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return _store
}
export function useStore(initialState) {
const store = useMemo(() => initializeStore(initialState), [initialState])
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