0

Друзья всем привет, кто работал с Redux-toolkit требуется помощь.

Я пытаюсь написать свою кастомную функцию которую буду передовать при вызове PayloadCreator в Async Thunk, пример:

export const updateCurrentBrand = createAsyncThunk('brand/updateCurrentBrand', protectRequest(brandApi, 'POST')) 

Тело функции protectRequest:

export const protectRequest = (url: string, method: string) => {
    return ({id, data}: any, thunkAPI: any) => {
        fetch(url + (id ? id : ''), {
            method: method,
            body: JSON.stringify(data),
            signal: thunkAPI.signal,
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
            .then(async (response) => {
                console.log(thunkAPI.signal)
                try {
                    const data = await response.json();
                    if (response.status === 200) {
                        return data
                    }
                    if (response.status === 400) {
                        return thunkAPI.rejectWithValue(data)
                    }
                }
                catch(err) {
                    let error = err
                    if (!error.response) {
                        throw err
                    }
                    return thunkAPI.rejectWithValue(response)
                }

            })
    }
} 

В документации есть пример для обратки ошибок уже в компоненте, в моем случае ошибки не попадает и приложение думает что все хорошо, пример проверки в компоненте:


formikHelpers.validateForm(newValues)
    .then( async () => {
        const resultAction: any = await dispatch(updateModel({id, data: values}))
        if (updateModel.fulfilled.match(resultAction)) {
            enqueueSnackbar('Модель успешно обновлена', {variant: 'success'})
            dispatch(getBrand())
            goBack()
        } else {
            if (resultAction.payload) {
                const errorMessage: string = resultAction.payload.data.errors.title
                // Being that we passed in ValidationErrors to rejectType in `createAsyncThunk`, those types will be available here.
                formikHelpers.setSubmitting(false)
                enqueueSnackbar(`Ошибка:${errorMessage}, модель была обновлена ранее`, {variant: 'error'})
                goBack()
            }
        }
    }) 

Как в данном случае обработать ошибки с сервера, заранее спасибо

1 ответ 1

0

Нашел оптимальное решение данного вопроса

export const protectRequest = (url: string, method: string) => {
    return async ({id, data}: {id: string, data: object}, thunkAPI: any) => {
        const response = await fetch(url + (id ? id : ''), {
            method: method,
            body: JSON.stringify(data),
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
        try {
            const payload = await response.json();
            if (response.status === 200) {
                return payload
            }
            if (response.status === 400) {
                return thunkAPI.rejectWithValue(payload)
            }
        }
        catch(e) {}
        if(response.status === 401) {
            return thunkAPI.rejectWithValue(new Error('Ошибка авторизации'))
        }
        return thunkAPI.rejectWithValue(new Error('Ошибка сервера'))
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.