33
loading...
This website collects cookies to deliver better user experience
Traditional Way
was to pass that itemCode as an prop to B, then C, and at last to D.😎😎 How Redux Solves
is that it makes an store for an application, which holds all the states of application at one place. So when itemCode is generated at component A, insted of passing it as an props to all the way down to component D, component A will store that itemCode in the Store, and component D will fetch itemCode value form that Store.First let's setup the basic project
npx create-react-app todo_redux
npm install react-redux redux
/src
/action-types.js
and /todo.js
/todo.js
store.js
what should be done
on calling specific commands which developer has made. Like in our case, their are 2 action which is made,import { ADD_TODO } from "./action-types";
export const addTodo = (todo) => ({
type: ADD_TODO,
payload: todo,
});
how to do ?
is defined in reducer file. For our case, what to do with the state/store when an addTodo action is recieved == We have to add an todo with details recieved from action package into out store which has some previous todos and return the updated state of todos in out store.import { ADD_TODO } from "../action/action-types";
const initialState = [];
export const todos = (state = initialState, action) => {
switch (action.type) {
case ADD_TODO:
return [...state, action.payload];
default:
return state;
}
};
import { createStore, combineReducers } from "redux";
import { todos } from "./reducer/todo";
const rootReducer = combineReducers(
todos
});
const store = createStore(rootReducer);
export default store;
combineReducers
we combine them into 1 reducer and with createStore
we create an store for the application.<Provider store={store}> all the components comes here </Provider >
react-redux
magic which handles all the work and store is passed it, which is imported from store file.const mapStateToProps = (state) => ({
todos: state.todos,
});
const TodoForm = ({ todos }) => {};
const mapDispatchToProps = (dispatch) => ({
addTodo: (todo) => {
dispatch(addTodo(todo));
},
});
const TodoForm = ({ addTodo }) => {};