Search code examples
javascriptreactjsreduxreact-hooksredux-thunk

REDUX: Error: Actions may not have an undefined "type" property. Have you misspelled a constant?


I'm learning Redux, and I am very confused about what is going on here. I am using thunk and GET_ITEMS is in my reducer so I'm not sure what I have done wrong? The error is in the dispatch(getItemsAction());

Redux.js

function reducer(state, action) {
    switch (action.type) {
        case 'GET_ITEMS':
            return {
                ...state,
                items: action.payload,
                loading: false,
            };
        case 'ADD_ITEM':
            return {
                ...state,
                items: [...state.items, action.payload],
            };
        case 'DELETE_ITEM':
            return {
                ...state,
                items: state.items.filter(item => item.id !== action.payload),
            };
        case 'ITEMS_LOADING':
            return {
                ...this.state,
                loading: true,
            };
        default:
            return state;
    }
}

export const getItemsAction = () => ({
    return(dispatch) {
        axios.get('api/items').then(response => {
            console.log(response);
            dispatch({ type: 'GET_ITEMS', payload: response.data });
        });
    },
});

ShoppingList.js

import { addItemAction, deleteItemAction, getItemsAction } from '../redux';

export default function ShoppingList() {
    const items = useSelector(state => state.items);

    const dispatch = useDispatch();
    const addItem = name => dispatch(addItemAction(name));
    const deleteItem = id => dispatch(deleteItemAction(id));

    useEffect(() => {
        dispatch(getItemsAction());
    }, []);

Solution

  • in the top code you returned the dispatch in incorrect way but actually you need to call dispatch like cb for example in javascript we do somthing like this

    const myfunc = () => cb => {
        cb('OK')
    };
    

    its callback in javascript and you have to return dispatch like callback to work correct

    export const getItemsAction = () => dispatch => {
        axios.get('api/items').then(response => {
                dispatch({
                    type: 'GET_ITEMS',
                    payload: response.data
                })
        });
    };
    

    at the end dont forgot to get axios response data with response.data