Skip to content

Instantly share code, notes, and snippets.

@rifqirosyidi
Last active December 3, 2020 08:24
Show Gist options
  • Save rifqirosyidi/2bd7cfe6c2a837a5fea43ec532906c3a to your computer and use it in GitHub Desktop.
Save rifqirosyidi/2bd7cfe6c2a837a5fea43ec532906c3a to your computer and use it in GitHub Desktop.
Learn the basic of Redux in one file.
const {createStore} = Redux;
const initState = {
todos: [],
posts: []
}
function myReducer(state=initState, action) {
if (action.type === 'ADD_TODO') {
return {
...state,
todos: [...state.todos, action.payload]
}
}
if (action.type === 'ADD_POST') {
return {
...state,
posts: [...state.posts, action.payload]
}
}
}
const store = createStore(myReducer);
store.subscribe(() => {
console.log("STATE UPDATED");
console.log(store.getState());
})
const todoAction = { type: 'ADD_TODO', payload: 'Buy Milk' }
store.dispatch({type: 'ADD_TODO', payload: "Sleep More"})
store.dispatch({type: 'ADD_TODO', payload: "Go to Store"})
store.dispatch({type: 'ADD_POST', payload: "This is a post, not a todo"})
store.dispatch({type: 'ADD_POST', payload: "This is a second post, not the first one"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment