import {SampleJoke} from "../../model/SampleJoke"; import {setCategoriesList, setJokesList} from "../actions/JokeAction"; import {Category} from "../../model/Category"; export const getList = (uri:string, constructor : (json:any) => TList, setList: (list: TList[]) => any) => { //In order to use await your callback must be asynchronous using async keyword. return async dispatch => { //Then perform your asynchronous operations. try { const promise = await fetch(uri); //Then use the json method to get json data from api/ const listJson = await promise.json(); const List: TList[] = listJson.map(elt => constructor(elt)); dispatch(setList(List)); } catch (error) { console.log('Error---------', error); } } } export const getLastSampleJokesList = () => { return getList('https://iut-weather-api.azurewebsites.net/jokes/lasts', (elt) => new SampleJoke(elt["id"], elt["type"], elt["setup"], elt["image"]), (list) => setJokesList(list)) } export const getCategoriesList = () => { return getList('https://iut-weather-api.azurewebsites.net/jokes/categories/top', (elt) => new Category(elt["name"], elt["number"]), (list) => setCategoriesList(list)) } export const getSampleJokesList = () => { return getList('https://iut-weather-api.azurewebsites.net/jokes', (elt) => new SampleJoke(elt["id"], elt["type"], elt["setup"], elt["image"]), (list) => setJokesList(list)) }