Mirko Albanese
Mirko Albanese

Reputation: 73

Redux initial state from API issue

My issue is that I want to fetch all products from the database and set them into the Redux initial state, to do this I did an action SET_PRODUCTS_LIST and in the action. payload I simply passed the products fetched in the component (I am using next js), all works fine but when I try to fire another action like ADD_PRODUCT_TO_CART the products in the initial state are gone which it results impossible to add more than 1 product to the cart.

Inside my component:

function Header({ cartProps, setProducts }) {
  useEffect(async () => {
    const products = await getProducts();
    setProducts(products);
  }, []);
}

const mapStateToProps = (state) => {
  return {
    cartProps: state.cartState,
  };
};

export default connect(mapStateToProps, {
  setProducts,
})(Header);

the action to set products:

import { SET_PRODUCTS_LIST } from "./types";

export const setProducts = (products) => {
  return (dispatch) => {
    dispatch({
      type: SET_PRODUCTS_LIST,
      payload: products,
    });
  };
};

My cart reducer:

const initialState = {
  itemNumbers: 0,
  cartCost: 0,
  products: [],
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case SET_PRODUCTS_LIST: {
      return {
        ...state,
        products: action.payload,
      };
    }

    case ADD_PRODUCT_TO_CART: {
      //let addQuantity = {
      // ...state.products.filter((p) => p.productName === action.paylaod),
      //   };
      console.log(state.products);
      return {
        itemNumbers: state.itemNumbers + 1,
      };
    }

    default:
      return state;
  }
};

export default reducer;

maybe I am completely doing wrong the logic about fetching the products in order to have them in the initial state.

Upvotes: 1

Views: 148

Answers (1)

Sedoyjan
Sedoyjan

Reputation: 164

const initialState = {
  itemNumbers: 0,
  cartCost: 0,
  products: [],
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case SET_PRODUCTS_LIST: {
      return {
        ...state,
        products: action.payload,
      };
    }

    case ADD_PRODUCT_TO_CART: {
      //let addQuantity = {
      // ...state.products.filter((p) => p.productName === action.paylaod),
      //   };
      console.log(state.products);
      return {
        ...state
        itemNumbers: state.itemNumbers + 1,
      };
    }

    default:
      return state;
  }
};

export default reducer;

You should always return state but in ADD_PRODUCT_TO_CART case you return only

{
  itemNumbers: state.itemNumbers + 1,
}

so you need to add ...state before itemNumbers: state.itemNumbers + 1,

Upvotes: 2

Related Questions