lxaw/DataDock

update cart number automatically updates when add to cart

Closed this issue · 2 comments

lxaw commented
update cart number automatically updates when add to cart
lxaw commented

This should be using redux. Something like:

import { createStore, combineReducers } from 'redux';

// Initial state
const initialCartState = {
  numCartItems: 0,
};

// Action types
const UPDATE_CART_ITEMS = 'UPDATE_CART_ITEMS';

// Action creators
export const updateCartItems = (count) => ({
  type: UPDATE_CART_ITEMS,
  payload: count,
});

// Reducer
const cartReducer = (state = initialCartState, action) => {
  switch (action.type) {
    case UPDATE_CART_ITEMS:
      return {
        ...state,
        numCartItems: action.payload,
      };
    default:
      return state;
  }
};

// Combine reducers if you have more
const rootReducer = combineReducers({
  cart: cartReducer,
});

// Create store
const store = createStore(rootReducer);

export default store;


---
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

something like this