Skip to content

Instantly share code, notes, and snippets.

@vinicius91
Last active July 31, 2019 16:56
Show Gist options
  • Select an option

  • Save vinicius91/3b88e261199e7d3c5e7abceae204ffc4 to your computer and use it in GitHub Desktop.

Select an option

Save vinicius91/3b88e261199e7d3c5e7abceae204ffc4 to your computer and use it in GitHub Desktop.
Basic Store Structure
import { getCharacters, getFilteredCharacters } from "../service";
export const characterActionTypes = {
FETCH_CHARACTER_START: "FETCH_CHARACTER_START",
FETCH_CHARACTER_SUCCESS: "FETCH_CHARACTER_SUCCESS",
FETCH_CHARACTER_ERROR: "FETCH_CHARACTER_ERROR"
};
// Action Creators
export const createFetchCharactersStartAction = () => ({
type: characterActionTypes.FETCH_CHARACTER_START
});
export const createFetchCharactersSuccessAction = payload => ({
type: characterActionTypes.FETCH_CHARACTER_SUCCESS,
payload
});
export const createFetchCharactersErrorAction = payload => ({
type: characterActionTypes.FETCH_CHARACTER_ERROR,
payload
});
// Async Actions
export const fetchCharacters = () => {
return dispatch => {
dispatch(createFetchCharactersStartAction());
return getCharacters()
.then(fetchedCharacters => {
console.log("Here!");
dispatch(createFetchCharactersSuccessAction(fetchedCharacters));
})
.catch(err => dispatch(createFetchCharactersErrorAction(err.message)));
};
};
export const filterCharacters = payload => {
return dispatch => {
dispatch(createFetchCharactersStartAction());
return getFilteredCharacters(payload)
.then(fetchedCharacters => {
console.log("Here!");
dispatch(createFetchCharactersSuccessAction(fetchedCharacters));
})
.catch(err => dispatch(createFetchCharactersErrorAction(err.message)));
};
};
import { combineReducers, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import characters from "./reducer";
export const rootReducer = combineReducers({ characters });
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
trace: true,
traceLimit: 25
});
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(thunk))
);
export default store;
import { characterActionTypes } from "./actions";
const charactersInitialState = {
characters: [],
loading: false
};
const characterReducer = (state = charactersInitialState, action) => {
switch (action.type) {
case characterActionTypes.FETCH_CHARACTER_START:
return { ...state, loading: true };
case characterActionTypes.FETCH_CHARACTER_SUCCESS:
return { ...state, characters: action.payload, loading: false };
case characterActionTypes.FETCH_CHARACTER_ERROR:
return { ...state, loading: false };
default:
return state;
}
};
export default characterReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment