Created
July 13, 2017 13:23
-
-
Save carlosvini/5715fedb45f8b81a9d1ae2bd47c89619 to your computer and use it in GitHub Desktop.
Pseudo Redux code
This file contains hidden or 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
// Component | |
class CarList extends Component { | |
componentWillMount() { | |
this.props.fetchCars(); // dispatching an action creator | |
} | |
render() { | |
if (this.props.error) { | |
// show some message | |
} | |
this.props.cars.map(...); | |
} | |
} | |
function mapStateToProps(state) { | |
return { | |
cars: state.cars.all; | |
}; | |
} | |
// Actions | |
fetchCars() { // action creator | |
try { | |
const data = axios.get(); | |
return fetchCarsSuccess(data); | |
} catch (e) { | |
return fetchCarsError(e); | |
} | |
} | |
fetchCarsSuccess(data) { | |
return { // action // unnamed, identified by it's type | |
type: 'FETCH_CARS_SUCCESS', | |
payload: data | |
}; | |
} | |
fetchCarsError(e) { | |
return { // action // unnamed, identified by it's type | |
type: 'FETCH_CARS_ERROR', | |
payload: e | |
}; | |
} | |
// Middleware | |
function errorLogMidleware(state, action) { | |
if (action.payload instanceof Error) { | |
logItOnMyErrorTrackingApp(action.payload); | |
} | |
return state; | |
} | |
// Reducers | |
state: { | |
cars: carReducer(...) | |
} | |
const INITIAL_STATE = { | |
all: [], | |
loading: false, | |
error: null | |
}; | |
export default function carReducer(state = INITIAL_STATE, action) { // reducer | |
switch (action.type) { | |
case 'FETCH_CARS_SUCCESS': | |
return { | |
...state, // Object spread | |
all: action.payload, | |
loading: false, | |
error: null | |
}; | |
case 'FETCH_CARS_ERROR': | |
return { | |
...state, | |
loading: false, | |
error: action.payload | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment