# React+Redux action + reducer + usage
## Actions
`actions/index.js`
```javascript
export function actionFunction() {
/*do somethings with data*/
return {
type: 'SAMPLE_ACTION' /*action type name, best from constants folder*/
payload: data /*your data*/
}
}
```
## Reducers
`reducers/reducer_name.js`
```javascript
export default function(state = /*initial state*/ null, action) {
switch(action.type) {
/* use action names from costants */
case 'SAMPLE_ACTION': {
/* always return piece of app redux state */
/* never modify app state or any of its pieces */
return action.payload
}
}
}
```
Always use combineReducers from redux in `reducers/index.js`
```javascript
const rootReducer = combineReducers({
reducer_name: ReducerName
});
export default rootReducer;
```
## Usage
In your main js file `/index.js` import your combined reducers and use createStore method from redux
```jsx
const createStoreWithMiddleware = applyMiddleware()(createStore)
/*...*/
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
```
In your container, where you want to use that action use functions: `mapStateToProps` and `mapDispatchToProps` and
```jsx
/* you can use React.Component class as base or do functional component */
const ContainerName = (props) => {
return (
/*
use some jsx magic here, eg.
<img src={props.photo.image.source} onClick={() => props.doMagic()}/>
*/
)
}
function mapStateToProps(state) {
return { photo: state.photo }
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ doMagic: doMagic }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(ContainerName)
```