N
N
Neuro2019-06-20 03:05:38
typescript
Neuro, 2019-06-20 03:05:38

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

spoiler
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`);
    )
}

maybe someone knows the solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-20
@Riveran

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 question

Ask a Question

731 491 924 answers to any question