'react redux does not return updated state when component load
I have one reducer.I update store when user perform action.I get store data from redux store using hook.It return initialstate in default actions.How to return updated state in default actions.I get store data in one of my class component.Its work fine.It does not work only within functional component.please give any solution
productreducer.js
import { Types } from '../constants';
const initialState ={
data:[],
cartitems:0,
cartproducts:[],
total:0,
testcounter:0
}
export function product(state = initialState , action) {
console.log(state.cartproducts)
console.log(action.type)
switch (action.type) {
case Types.GETPRODUCT:
return {
...state,
data: action.payload,
};
case Types.ADD_TO_CART:
let addedproduct = state.cartproducts.find(item=> item._id === action.product._id)
console.log(state.cartproducts)
let newcount=state.cartitems+1
let newtotal=state.total+parseInt(action.product.variants[0].price)
action.product.quantity=1
action.product.totalprice=parseInt(action.product.variants[0].price)
return{
...state,
cartproducts: [...state.cartproducts, action.product],
cartitems : newcount,
total:newtotal
}
case Types.ADD_QUANTITY:
return {
...state,
cartproducts: state.cartproducts.map(item => item._id === action.product._id
? {
...item,
quantity: item.quantity + 1,
totalprice:item.totalprice + parseInt(item.variants[0].price),
}
: item
),
total:state.total+parseInt(action.product.variants[0].price)
};
case Types.REMOVE_QUANTITY:
return {
...state,
cartproducts: state.cartproducts.map(item => item._id === action.product._id
? {
...item,
quantity: item.quantity - 1,
totalprice:item.totalprice - parseInt(item.variants[0].price),
}
: item
),
total:state.total-parseInt(action.product.variants[0].price)
};
case Types.PLUS:
return {
...state,
testcounter:state.testcounter+1
}
case Types.MINUS:
return {
...state,
testcounter:state.testcounter-1
}
default:
return state
}
}
Solution 1:[1]
Well you can use useSelector hook from react-redux for accessing updated state using below code:
const abc = () => {
const data = useSelector(state => state.stateName)
}
export default abc
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharmik Patel |
