import {SampleJoke} from "../../model/SampleJoke"; import {setCategoriesList, setJokeById, 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 getItem = (uri:string, constructor : (json:any) => TItem, setItem: (item: TItem) => 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 Json = await promise.json(); const Item: TItem = constructor(Json); dispatch(setItem(Item)); } 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/samples', (elt) => new SampleJoke(elt["id"], elt["type"], elt["setup"], elt["image"]), (list) => setJokesList(list)) } export const getJokeById = (id) => { return getItem('https://iut-weather-api.azurewebsites.net/jokes/samples/' + id , (elt) => new SampleJoke(elt["id"], elt["type"], elt["setup"], elt["image"]), (item) => setJokeById(item)) }