Skip to content

Instantly share code, notes, and snippets.

@patwadeepak
Created July 23, 2021 07:09
Show Gist options
  • Save patwadeepak/258e73f8513e70237ac4aefb213e5e5d to your computer and use it in GitHub Desktop.
Save patwadeepak/258e73f8513e70237ac4aefb213e5e5d to your computer and use it in GitHub Desktop.
The Redux Way - Boilerplate
// this is inside reducers folder. do not confuse this with react app's index.js
import { combineReducers } from "redux";
import postReducer from "./postReducer";
export default combineReducers({
posts: postReducer,
});
import { FETCH_POSTS, NEW_POST } from "./types";
export const fetchPosts = (postsData) => {
return {
type: FETCH_POSTS,
payload: postsData,
};
};
export const createNewPost = (postData) => {
return {
type: NEW_POST,
payload: postData,
};
};
import { FETCH_POSTS, NEW_POST } from "../actions/types";
const initialState = {
items: [],
item: { title: "", body: "" },
};
const postReducer = (state = initialState, action) => {
if (action.type === FETCH_POSTS) {
return {
...state,
items: action.payload,
};
} else if (action.type === NEW_POST) {
return {
...state,
items: [action.payload, ...state.items],
};
} else return state;
};
export default postReducer;
import { createStore } from "redux";
import rootReducer from "./reducers";
const initialState = {
posts: {
items: [],
item: { title: "some title", body: "some body" },
},
};
const store = createStore(rootReducer, initialState);
export default store;
export const FETCH_POSTS = "FETCH_POSTS";
export const NEW_POST = "NEW_POST";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment