Skip to content

Instantly share code, notes, and snippets.

@kwonghung-YIP
Created June 18, 2020 18:19
Show Gist options
  • Save kwonghung-YIP/00f23fa294a3377ff30ab75402ff7d0f to your computer and use it in GitHub Desktop.
Save kwonghung-YIP/00f23fa294a3377ff30ab75402ff7d0f to your computer and use it in GitHub Desktop.
Counter sample for using react-redux
import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import { createStore, combineReducers } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const reducer = combineReducers({
counter: (state = 0, action) => {
switch (action.type) {
case "INCR":
return state + 1;
case "DECR":
return state - 1;
default:
return state;
}
},
lastUpdate: (state = null, action) => {
switch (action.type) {
case "INCR":
return new Date();
case "DECR":
return new Date();
default:
return state;
}
}
});
const store = createStore(reducer);
function Counter(props) {
const { counter, lastUpdate } = useSelector( state => state );
const dispatch = useDispatch();
return (
<React.Fragment>
<p>{counter}</p>
<p>{lastUpdate===null?"N/A":lastUpdate.toDateString()}</p>
<button type="button" onClick={e=>{dispatch({type:"INCR"})}}>Incr +</button>
<button type="button" onClick={e=>{dispatch({type:"DECR"})}}>Decr -</button>
</React.Fragment>
);
}
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Counter/>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment