@zpnk
@wedgies
source: youhavetolearncomputers.com
source: youhavetolearncomputers.com
source: youhavetolearncomputers.com
// Action Creators
const incrementCounter = () => ({
type: 'INCREMENT'
})
const decrementCounter = () => ({
type: 'DECREMENT'
})
// Reducer
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
// Store
import {createStore} from 'redux'
const store = createStore(counter)
// Dispatch actions
store.dispatch(incrementCounter())
// Listen for changes
store.subscribe(render)
// Get the current state
const state = store.getState()
import React from 'react'
import {render} from 'react-dom'
import {Provider} from 'react-redux'
import {createStore} from 'redux'
import counterReducer from './reducers'
import Counter from './containers/Counter'
const store = createStore(counterReducer)
render(
<Provider store={store}>
<Counter />
</Provider>,
document.getElementById('root')
)
import React from 'react'
import {connect} from 'react-redux'
import {incrementCounter, decrementCounter} from '../actions'
const Counter = ({count, incrementCounter, decrementCounter}) => (
<div>
<h1>{count}</h1>
<button onClick={incrementCounter}>+</button>
<button onClick={decrementCounter}>-</button>
</div>
)
const mapStateToProps = ({count}) => ({count})
const mapDispatchToProps = {incrementCounter, decrementCounter}
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
// store/index.js
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducers/index'
const store = createStore(
rootReducer,
applyMiddleware(thunk)
)
export default store
// actions/index.js
export const fetchSecretSauce = () => fetch('https://www.google.com/search?q=secret+sauce')
}
// middleware/api.js
export const CALL_API = 'Call_API'
export default store => next => action => {
const callApi = action[CALL_API]
if (typeof callApi === 'undefined') return next(action)
const {types, endpoint} = callApi
const [requestType, successType, failureType] = types
next({type: requestType})
fetch(endpoint)
.then(res => { return next({type: successType, res}) })
.catch(res => { return next({type: failureType, msg: 'Request failed}) })
}
// actions/index.js
export const loadQuestion = (id) => ({
[CALL_API]: {
types: [
QUESTION_LOAD_REQUEST,
QUESTION_LOAD_SUCCESS,
QUESTION_LOAD_FAILURE
],
endpoint: `/api/question/${id}`
}
})