modules/post.js
import { createAction, handleActions } from 'redux-actions'
import axios from 'axios'
import { applyPenders } from 'redux-pender'
function getPostAPI(postId) {
return axios.get(`https://jsonplaceholder.typicode.com/posts/${postId}`) }
const GET\_POST = 'GET\_POST'
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
export const getPost = createAction(GET\_POST, getPostAPI);
export const increment = createAction(INCREMENT)
export const decrement = createAction(DECREMENT)
const initialState = {
idx : 0,
data: {
title: '',
body: ''
}
}
const reducer = handleActions({
[INCREMENT] : (state, action) => ({
...state,
idx: state.idx++
}),
[DECREMENT] : (state, action) => ({
...state,
idx: state.idx--
})
}, initialState)
export default applyPenders(
reducer, [
{
type: GET_POST,
onSuccess: (state, action) => {
// 성공했을 때 해야 할 작업이 따로 없으면 이 함수 또한 생략해도 됩니다.
const { title, body } = action.payload.data;
return {
...state,
data: {
title,
body
}
}
}
}]
)
modules/index.js
import { combineReducers } from "redux";
import post from './post';
import { penderReducer } from 'redux-pender'
export default combineReducers({
post,
pender: penderReducer
})
store.js
import { createStore, applyMiddleware } from "redux";
import modules from './modules'
import penderMiddleware from 'redux-pender'
const store = createStore(modules, applyMiddleware(penderMiddleware()))
export default store
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import \* as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(, 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](https://bit.ly/CRA-PWA)
serviceWorker.unregister();
App.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux'
import './App.css';
import \* as postActions from './modules/post'
class App extends Component{
render(){
const { PostActions, post } = this.props
console.log(post)
return (
<div className="App">
<h1>1</h1>
<button>+</button>
<button>-</button>
<hr/>
<div></div>
<div></div>
</div>
);
}
}
export default connect(
(state) => ({ post: state.post }),
(dispatch) => ({ PostActions : bindActionCreators(postActions, dispatch) })
)(App);