I am implementing a shop cart using react-redux. I got two reducers, 1.To fetch cart data from DB 2. To Carry out various cart operations.
My doubt is after achieving data from DB through the first reducer, how will I access that data through the 2nd reducer in order to carry out different cart operations ?
Reducer 1 - Fetch Data from DB
const initialState={
loading:false,
items:[],
error:false
}
const CartFetch=(state=initialState,action)=>{
switch(action.type){
case FETCHDATA : return {
...state,loading:true ,error:false
};
case FETCHSUCCESS: return {
...state,loading:false,
items:[...action.payload]
};
case FETCHERROR : return {
...state,loading:false,error:true
};
default: return state;
}
}
Fetch Actions
const fetch=()=>{
return {
type:FETCHDATA
}
}
const success=(user)=>{
return {
type:FETCHSUCCESS,
payload:user
}
}
const error=()=>{
return {
type:FETCHERROR
}
}
const fetchCartData=()=>{
const {id}=getCurrentUser();
return (dispatch)=>{
dispatch(fetch());
axios.get(`${api.userOperations}/cart/${id}`,{
headers:{'Authorization': getJwt()}
}).then(({data})=>{
dispatch(success(data));
}).catch(()=>{
dispatch(error())
})
}
}
Reducer 2 - Cart Operations
const CartHandle=(state= ..?.. ,action)=>{
switch(action.type){
case ADD_TO_CART :
return {
......
};
case INCREMENT_CART : return {
....
};
case DECREMENT_CART: return {
......
};
case REMOVE_FROM_CART : return {
.....
};
default: return state;
}
}
}
Here in Reducer 2 how will I access the pass the data which I fetched in Reducer 1 ? Or easy there any better way of implementing what I m trying to ?
Combine Reducers
const allReducer=combineReducers({
Cart:CartFetch,
CartOperations: CartHandle
});
Store
const countStore=createStore(allReducer,applyMiddleware(thunk));
<Provide store={store}>
...App.js...
</Provider>