Search code examples
javascriptreactjsreduxreact-reduxmern

How to use reducer in redux in react


I am using Redux for state management, I have faced an issue in reducer function here is the image of my console, You can see the Product Action is providing my data but the reducer is not passing on my function

enter image description here

here is my code of ProductAction:

export const getProductsbyFind = (myvariable) =>async (dispatch)=>{
    try {
        console.log(myvariable)
        dispatch({type: ALL_PRODUCTS_REQUEST_BY_ID})
        const{ data } = await axios.get(`/api/v1/product/${myvariable}`)
        console.log(data)
        dispatch({
            type: ALL_PRODUCTS_SUCCESS_BY_ID,
            payload: data
        })
        
    } catch (error) {
        dispatch({
            type:ALL_PRODUCTS_FAIL,
            payload: error.response.data.message
        })
        
    }
}

here is the code of Reducer:

export const productReducersById = (state = { products: [] }, action) => {
    switch (action.type) {
        case ALL_PRODUCTS_REQUEST_BY_ID:
            return {
                loading: true,
                products: []
            }
        case ALL_PRODUCTS_SUCCESS_BY_ID:
            return {
                loading: false,
                products: action.payload.products,
                productsCount: action.payload.productsCount
            }
        case UPDATE_QUANTITY_BY_ID:
            const { index, quantity } = action.payload;
            const prods = state.products.map((p, i) => {
                if (i !== index)
                    return p;
                return {
                    ...p,
                    quantity
                }
            });
            return {
                loading: true,
                products: prods
            }

        case ALL_PRODUCTS_FAIL_BY_ID:
            return {
                loading: false,
                error: action.payload
            }
        case CLEAR_ERRORS_BY_ID:
            return {
                ...state,
                error: null
            }
        default:
            return state
    }
}

here is the code of my page where I want to get my data:

  const { loading, products, error, productCount } = useSelector(state => state.products);
  console.log(products)
  useEffect(() => {
    dispatch(getProductsbyFind(myvariable));
  }, [dispatch])

Solution

  • You have a typo in your reducer:

      case ALL_PRODUCTS_SUCCESS_BY_ID:
          return {
              loading: false,
    -         products: action.payload.products,
    +         products: action.payload.product,
              productsCount: action.payload.productsCount
          }
    

    (Also, productsCount does not exist in your payload, so that will become undefined.)