Skip to content

Instantly share code, notes, and snippets.

@egin10
Last active October 3, 2019 04:10
Show Gist options
  • Save egin10/1e71dee08ec79450cc9b3f055ff5c3f0 to your computer and use it in GitHub Desktop.
Save egin10/1e71dee08ec79450cc9b3f055ff5c3f0 to your computer and use it in GitHub Desktop.
Create Redux for ReactJs
export const ADD_TODO = 'ADD_TODO'
export const EDIT_TODO = 'EDIT_TODO'
export const DELETE_TODO = 'DELETE_TODO'
// Use connect to use Store and Dispatch
import { connect } from'react-redux'
// Use todoAction from todoAction.js
import { addTodo } from './todoAction'
/*
use this syntax to access the store => this.state.todos
component(this.state.todos)
*/
/* This syntax is use for access data in store */
const mapStateToProps = state => {
return {
// Get store from todoReducer.js
todos: state.todoReducer.todos
}
}
/* This syntax is use for access action and send payload to dispatch */
const mapDispatchToProps = dispatch => {
return {
addTodos: (todo) => dispatch(addTodo(todo))
}
}
/* This syntax is use for connect store and dispatch to this Component */
export default connect(mapStateToProps, mapDispatchToProps)(Component)
import React, {Component} from 'react';
// Import provider to wrapping store and dispatch to Component
import { Provider } from 'react-redux'
// Import store
import store from './store'
class App extends Component{
render() {
return (
// Send store to component using Provider
<Provider store={store}>
<div className="App container">
<Component />
</div>
</Provider>
);
}
}
// Import package to createStore and combineReducer more than one reducer
import { createStore, combineReducers } from 'redux'
// Combine more than one Reducer
const rootReducer = combineReducers({
todoReducer: todoReducer,
noteReducer: noteReducer
})
// Create store
const store = createStore(rootReducer)
// Create store to use Redux Dev Tools on Chrome
// const store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
export default store
// Import action who has define in actionTypes.js in above
import * as actionTypes from './actionTypes'
export const addTodo = (todo) => ({
type: actionTypes.ADD_TODO,
payload: todo
})
export const editTodo = (payload) => ({
type: actionTypes.EDIT_TODO,
payload: payload
})
export const deleteTodo = (index) => ({
type: actionTypes.DELETE_TODO,
payload: index
})
// Init state for Todos
const initialState = {
todos: []
}
// Init Reducer for Todos
const todoReducer = (state = initialState, action) => {
switch(action.type) {
case actionTypes.ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload]
}
case actionTypes.EDIT_TODO:
return {
...state,
//statement to edit todo...
}
case actionTypes.DELETE_TODO:
return {
...state,
//statement to delete todo...
}
default :
return state
}
}
export default todoReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment