I have this simple case:
import { createSlice } from '@reduxjs/toolkit';
export const cartSlice = createSlice({
name: 'cartItems',
initialState: {
cartItems: 0
},
reducers: {
updateCart: (state, action) => {
console.log('action', action.payload);
state.cartItems = action.payload;
},
},
});
export const { updateCart } = cartSlice.actions;
export default cartSlice.reducer;
Then I try to call it:
updateCart(100);
And the updateCart action is not called at all. There are no errors in the console and the store is:
import { configureStore } from '@reduxjs/toolkit';
import authSlice from './authSlice';
import tshirtsSlice from './tshirtsSlice';
import saveOrderSlice from './saveOrderSlice';
import cartSlice from './cartSlice';
export const store = configureStore({
reducer: {
user: authSlice,
tshirts: tshirtsSlice,
order: saveOrderSlice,
cartItems: cartSlice,
},
});
What is wrong? Thank you!
CodePudding user response:
It's not how redux works.
In component body you need to get dispatch:
const dispatch = useDispatch()
And call with action as argument:
dispatch(updateCart(100))
To get current state you need to use selector:
const cartItems = useSelector(state => state.cartItems)
More here: quick-start-redux
CodePudding user response:
I hope you have installed "react-redux", if not then install it
Then the component from where you want to dispatch an action, you have to import useDispatch first
So your component will look something like this
import { useDispatch } from "react-redux"
import { updateCart } from "./cart.js"
const func = () => {
const dispatch = useDispatch()
const updateCart = () => {
dispatch(updateCart(100))
}
return (
<button onClick={updateCart}>UpdateCart</button>
)
}
And change your store too,
export const store = configureStore({
reducer: {
user: authSlice.reducer,
tshirts: tshirtsSlice.reducer,
order: saveOrderSlice.reducer,
cartItems: cartSlice.reducer,
},
});