Skip to content

Instantly share code, notes, and snippets.

@carlosvini
Created July 13, 2017 13:23
Show Gist options
  • Save carlosvini/5715fedb45f8b81a9d1ae2bd47c89619 to your computer and use it in GitHub Desktop.
Save carlosvini/5715fedb45f8b81a9d1ae2bd47c89619 to your computer and use it in GitHub Desktop.
Pseudo Redux code
// 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