Answer the question
In order to leave comments, you need to log in
How to make an asynchronous request in redux using Type Script?
Good afternoon, I can not understand what is the error and what am I doing wrong when requesting the server
import * as constants from './../constants/index';
import { Dispatch } from 'react';
import Axios from 'axios';
export interface IgetApiData {
type: constants.GET_API_DATA;
data: any;
loading: boolean;
}
export interface IpendingApiData {
type: constants.PENDING_API_DATA;
loading: boolean;
}
function setNewsDataFetch(data: string, loading: boolean): IgetApiData {
return {
type: constants.GET_API_DATA,
data,
loading
}
}
function pendingNewsDataFetch(loading: boolean): IpendingApiData{
return {
type: constants.PENDING_API_DATA,
loading
}
}
export const getNewsDataFetch = () => (dispatch: Dispatch<IgetApiData | IpendingApiData>) = {
dispatch(pendingNewsDataFetch(true))
return (
const fetchApiNews = await Axios.get(`https://api.dtf.ru/v1.6/news/default/recent?count=1`);
)
}
Answer the question
In order to leave comments, you need to log in
1. The await operator can only be used in asynchronous functions
2. Your return block is not valid.
interface FetchNewsDataSucceededAction {
type: typeof FETCH_NEWS_DATA_SUCCEEDED;
payload: News[];
}
interface FetchNewsDataFailedAction {
type: typeof FETCH_NEWS_DATA_FAILED;
payload: MappedError;
}
type NewsActionTypes = FetchNewsDataSucceededAction |
Action<typeof FETCH_NEWS_DATA_REQUEST> |
FetchNewsDataFailedAction;
const fetchNewsDataRequest = (): NewsActionTypes => ({
type: FETCH_NEWS_DATA_REQUEST,
});
const fetchNewsDataSucceeded = (payload: News[]): NewsActionTypes => ({
type: FETCH_NEWS_DATA_SUCCEEDED,
payload,
});
const fetchNewsDataFailed = (payload: MappedError): NewsActionTypes => ({
type: FETCH_NEWS_DATA_FAILED,
payload,
});
export const fetchNewsData = (): : ThunkAction<Promise<void>, {}, {}, AnyAction> =>
async (dispatch: ThunkDispatch<{}, {}, NewsActionTypes>): Promise<void> => {
try {
const { data } = await Axios.get(`https://api.dtf.ru/v1.6/news/default/recent?count=1`);
dispatch(fetchNewsDataSucceeded(data));
} catch (error) {
dispatch(fetchNewsDataFailed(mapAxiosError(error)));
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question