ddimonn8080
@ddimonn8080

Почему срабатывают оба dispatch в react/redux?

Здравствуйте в react приложении делаю запрос на загрузку данных о продукте с помощью axios
resources/js/actions/products.js
import {
    SET_PRODUCTS,
    SET_PRODUCT_SINGLE,
    SET_PRODUCT_BY_SLUG,
    SET_PRODUCT_BY_SLUG_SUCCEEDED,
    SET_PRODUCT_BY_SLUG_FAILED,
    SET_PRODUCT_COMMENTS,
    SHOW_ALL,
    BESTSELLER,
    FACE,
    BODY,
    SCRUB
} from './types';

export const setProducts = products => ({
    type: SET_PRODUCTS,
    payload: products
});

export const setProductSingle = product => ({
    type: SET_PRODUCT_SINGLE,
    payload: product
});

export const setProductComments = comments => ({
    type: SET_PRODUCT_COMMENTS,
    payload: comments
});

/*export const fetchProductData = url => {
    return dispatch => {
        axios.get(url)
            .then(({data}) => {
                dispatch(setProductSingle(data))
            });
    }
};*/

export const setProductBySlug = slug => {
    return async dispatch => {
        dispatch({ type: SET_PRODUCT_BY_SLUG });

        /*axios.get(`/api/products/${slug}`)
            .then(({data}) => {
                dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data });
            }).catch(err => {
                dispatch({ type: SET_PRODUCT_BY_SLUG_FAILED, payload: err });
            });*/

        try {
            const { data } = await axios.get(`/api/products/${slug}`);
            dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data });
        } catch (err) {
            dispatch({ type: SET_PRODUCT_BY_SLUG_FAILED, payload: err });
        }
    };
}

export const CategoryFilters = {
    SHOW_ALL: SHOW_ALL,
    BESTSELLER: BESTSELLER,
    FACE: FACE,
    BODY: BODY,
    SCRUB: SCRUB,
};

resources/js/reducers/products.js

import {
    SET_PRODUCTS,
    SET_PRODUCT_SINGLE,
    SET_PRODUCT_BY_SLUG,
    SET_PRODUCT_BY_SLUG_SUCCEEDED,
    SET_PRODUCT_BY_SLUG_FAILED,
    SET_PRODUCT_COMMENTS
} from '../actions/types';

const INITIAL_STATE = {
    isReady: false,
    isSingleReady: false,
    isSingleLoading: false,
    isCommentsReady: false,
    items: [],
    product: {},
    comments: [],
    error: null,
};

export default function (state = INITIAL_STATE,action){
    switch (action.type) {
        case SET_PRODUCTS:
            return {
                ...state,
                items: action.payload,
                isReady: true
            };
        case SET_PRODUCT_SINGLE:
            return {
                ...state,
                product: action.payload,
                isSingleReady: true,
            };
        case SET_PRODUCT_BY_SLUG:
            return {
                ...state,
                isSingleReady: false,
                isSingleLoading: true,
                error: null,
            };

        case SET_PRODUCT_BY_SLUG_SUCCEEDED:
            return {
                ...state,
                product: action.payload,
                isSingleReady: true,
                isSingleLoading: false,
                error: null,
            };

        case SET_PRODUCT_BY_SLUG_FAILED:
            return {
                ...state,
                isSingleReady: false,
                isSingleLoading: false,
                error: action.payload,
            };

        case SET_PRODUCT_COMMENTS:
            return {
                ...state,
                comments: action.payload,
                isCommentsReady: true,
            };
        default:
            return state;
    }
}

Вот весь код

Проблема в том что если ввести неправильный slug продукта то dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data }); срабатывает все равно.

5cbd6edea937f793956357.png
Так тоже срабатывает
export const setProductBySlug = slug => {
    return async dispatch => {
        dispatch({ type: SET_PRODUCT_BY_SLUG });

        axios.get(`/api/products/${slug}`)
            .then(({data}) => {
                dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data });
            }).catch(err => {
                dispatch({ type: SET_PRODUCT_BY_SLUG_FAILED, payload: err });
            });
    };
}

если вывести data
export const setProductBySlug = slug => {
    return async dispatch => {
        dispatch({ type: SET_PRODUCT_BY_SLUG });

        /*axios.get(`/api/products/${slug}`)
            .then(({data}) => {
                dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data });
            }).catch(err => {
                dispatch({ type: SET_PRODUCT_BY_SLUG_FAILED, payload: err });
            });*/

        try {
            const { data } = await axios.get(`/api/products/${slug}`);
            console.log( data );
            dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data });
        } catch (err) {
            dispatch({ type: SET_PRODUCT_BY_SLUG_FAILED, payload: err });
        }
    };
}

выводит {product: null, productAttachments: Array(0)}
если проверить на product
export const setProductBySlug = slug => {
    return async dispatch => {
        dispatch({ type: SET_PRODUCT_BY_SLUG });
        try {
            const { data } = await axios.get(`/api/products/${slug}`);

            if(data.product){
                dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data });
            }
        } catch (err) {
            dispatch({ type: SET_PRODUCT_BY_SLUG_FAILED, payload: err });
        }
    };
}

то
dispatch({ type: SET_PRODUCT_BY_SLUG_SUCCEEDED, payload: data });

не отправляется но и
dispatch({ type: SET_PRODUCT_BY_SLUG_FAILED, payload: err });
тоже не отправляется.
Я так понял ошибка не воспринимается как ошибка.
В чем может быть проблема?
  • Вопрос задан
  • 158 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы