Miltosh
Miltosh

Reputation: 91

Cannot read property 'type' of undefined in Redux

i'm write react functional component, which should get some data from server. I'm use redux, but i get an error "Cannot read property 'type' of undefined"

Help me please find my mistake

This is my react component, Products.js. I think there may be errors in the export part. Also parent component Products.js (App.js) has wrapped on Provider

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchProducts } from '../actions/productActions';
import { productsReducer } from '../reducers/productReducers'


function Products({ store, products, cartItems, setCartItems }) {

    useEffect(() => {
        store.dispatch(productsReducer())
    })
    const [product, setProduct] = useState(null);

    return (
        <div>
            {
              !products
                ? (<div>Loading...</div>)
                :
                (<ul className="products">
                   {products.map(product => (
                      <li key={product._id}>
                        <div className="product">
                           <a href={"#" + product._id}>
                             <img src={product.image} alt={product.title} />
                                <p>{product.title}</p>
                           </a>
                             <div className="product-price">
                               <div>${product.price}</div>
                                  <button>Add To Cart</button>
                               </div>
                             </div>
                      </li>
                   ))}
                </ul>)
            }
        </div >
    )
}

export default connect((state) => ({ products: state.products.items }), {
     fetchProducts,
 })(Products);

This is my store.js

import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { productsReducer } from './reducers/productReducers';

const initialState = {};
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
    combineReducers({
        products: productsReducer,
    }),
    initialState,
    composeEnhancer(applyMiddleware(thunk))
)

export default store;

My reducer, and I am getting error in this file (Cannot read property 'type' of undefined), maybe, I making a transmission error 'action'

import { FETCH_PRODUCTS } from "../types";

export const productsReducer = (state = {}, action) => {
    switch (action.type) {
        case FETCH_PRODUCTS:
            console.log('it work!')
            return { items: action.payload };
        default:
            return state;
    }
};

My Action

import { FETCH_PRODUCTS } from "../types";

export const fetchProducts = () => async (dispatch) => {
    const res = await fetch("/api/products");
    const data = await res.json();
    console.log(data);
    dispatch({
        type: FETCH_PRODUCTS,
        payload: data,
    });
};

and my Types

export const FETCH_PRODUCTS = "FETCH_PRODUCTS"

This is are study project on redux, but in original teacher writte code on class component. Original code here and here

If i write class component like on source, everything is working, so i think this is a reason of mistake

Upvotes: 0

Views: 824

Answers (1)

oozywaters
oozywaters

Reputation: 1241

dispatch function expects redux action as an argument, not reducer. In your case:

import { fetchProducts } from '../actions/productActions';

function Products({ store, products, cartItems, setCartItems }) {

    useEffect(() => {
        store.dispatch(fetchProducts());
    })

    ...
}

Upvotes: 1

Related Questions