Last active
April 10, 2017 03:33
-
-
Save tylergraf/edfc444c80ab26fc9d85c835a1a7adf1 to your computer and use it in GitHub Desktop.
Basic Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// REDUCER | |
const counter = (state = 0, action) => { | |
switch (action.type) { | |
case 'INCREMENT': | |
return state + 1; | |
case 'DECREMENT': | |
return state - 1; | |
default: | |
return state; | |
} | |
} | |
// VIEW | |
const Counter = ({ | |
value, | |
onIncrement, | |
onDecrement | |
}) => ( | |
<div> | |
<h1>{value}</h1> | |
<button onClick={onIncrement}>+</button> | |
<button onClick={onDecrement}>-</button> | |
</div> | |
); | |
// ACTION TYPE CONSTANTS | |
const types = { | |
INCREMENT: 'INCREMENT', | |
DECREMENT: 'DECREMENT', | |
LOADING: 'LOADING' | |
} | |
// DISPATCHING OF ACTIONS | |
const mapDispatchToProps = (dispatch) => { | |
return { | |
onIncrement: () => { | |
dispatch({ | |
type: types.INCREMENT | |
}) | |
}, | |
onDecrement: () => { | |
dispatch({ | |
type: types.DECREMENT | |
}) | |
} | |
}; | |
}; | |
// REDUX VIEW BINDING | |
const mapStateToProps = (state) => { | |
return { | |
value: state | |
}; | |
} | |
// REDUX SETUP WITH REACT | |
const { connect } = ReactRedux; | |
const CounterContainer = connect( | |
mapStateToProps, | |
mapDispatchToProps | |
)(Counter); | |
// ACTION CREATOR | |
function incrementAction(){ | |
let action = { | |
type: types.INCREMENT | |
}; | |
return action; | |
} | |
// ASYNC ACTION CREATOR | |
function makeAsyncCallAction(num){ | |
return function(dispatch){ | |
let action = { | |
type: 'LOADING', | |
value: true | |
}; | |
dispatch(action); | |
serviceCall() | |
.then(data=>{ | |
let loadingAction = { | |
type: 'LOADING', | |
value: false | |
}; | |
dispatch(loadingAction); | |
let action = { | |
type: types.INCREMENT | |
}; | |
dispatch(action); | |
}) | |
} | |
} | |
/* | |
* Let's create a store. | |
*/ | |
const { createStore } = Redux; | |
const store = createStore(counter); | |
/* | |
* Finally, render the container, | |
* passing the store to it. | |
*/ | |
ReactDOM.render( | |
<CounterContainer store={store} />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment