I am really confused with this code. I just want to know how we pass parameters into the reducer(state, action)
function.
My main question is: how is the action parameter sent to the reducer function in my Comments.js file? I am not even importing ActionCreator.js file but I am able to use and comments returned payload values. How is this possible? Someone, please explain this to me in a transparent way.
Please excuse me for my code snippets editing
/ActionTypes.JS
export const ADD_COMMENT='ADD_COMMENT';
/ActionCreator.js
import * as ActionTypes from './ActionTypes';
export const addComment=(dishId, rating, author, comment)=>({
type:ActionTypes.ADD_COMMENT,
payload:{
dishId:dishId,
rating:rating,
author:author,
comment:comment
}
})
/Comments.js
import {COMMENTS} from "../shared/comments";
import * as ActionTypes from "./ActionTypes"
export const Comments=(state=COMMENTS, action)=>{
switch(action.type){
case ActionTypes.ADD_COMMENT:
var comment=action.payload;
comment.id=state.length
comment.date=new Date().toISOString()
console.log("Comment" + comment)
return state.concat(comment)
default:
return state;
}
}
When you have configured the redux store, you must have passed your reducers to store like here.
Now, if you see in example, they are calling store.dispatch(<some_action>)
. basically now your store knows what all reducers are there, it calls each of those reducers with the payload passed in dispatch function and return you an updated store. But mostlikely, you are not calling store.dispatch()
directly, you must be using connect()
to access store. As mentioned here, it connects your component to your redux store and now you dont have to call store.dispatch
instead you directly have access to dispatch function where you pass the payload and the same process as in 1st example continues. You don't have to import of call reducers, redux does it for you. Hope this make things clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With