Created
March 28, 2020 19:20
-
-
Save cjoecker/06cfd1e91bf4d4846b01217c04b887c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import {useDispatch, useSelector} from "react-redux"; | |
import {getFunFact} from "../services/FunFact_Actions"; | |
function FunFact() { | |
const dispatch = useDispatch(); | |
const {counterNumber} = useSelector(state => state.Counter); | |
const {funFact} = useSelector(state => state.FunFact); | |
return ( | |
<div className="App"> | |
<h4>{funFact}</h4> | |
<button | |
onClick={(e) => { | |
dispatch(getFunFact(counterNumber)) | |
}}> | |
Get Number Fun Fact | |
</button> | |
</div> | |
); | |
} | |
export default FunFact; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ThunkAction} from "redux-thunk"; | |
import {Action, Dispatch} from "redux"; | |
import axios, { AxiosError } from "axios"; | |
import {FunFactState} from "./FunFact_Reducer"; | |
export enum FunFactActionTypes { | |
SetFunFact = "SetFunFact", | |
} | |
export const getFunFact = (number:Number): ThunkAction<void, FunFactState, null, Action<string>> => async dispatch => { | |
await dispatch({ | |
type: FunFactActionTypes.SetFunFact, | |
payload: {funFact: "Loading..."} | |
}); | |
axios.get(`http://numbersapi.com/${number}`) | |
.then((answer) => { | |
dispatch({ | |
type: FunFactActionTypes.SetFunFact, | |
payload: {funFact: answer.data} | |
}); | |
}) | |
.catch((error: AxiosError) => { | |
dispatch({ | |
type: FunFactActionTypes.SetFunFact, | |
payload: {funFact: `Error: ${error.response}`} | |
}); | |
}) | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Reducer} from "redux"; | |
import {DispatchAction} from "./store"; | |
import {FunFactActionTypes} from "./FunFact_Actions"; | |
export class FunFactState { | |
funFact: string = ""; | |
} | |
export const FunFact_Reducer: Reducer<FunFactState, DispatchAction> = (state = new FunFactState(), action) => { | |
switch (action.type) { | |
case FunFactActionTypes.SetFunFact: | |
return { | |
...state, | |
funFact: action.payload.funFact || '', | |
}; | |
default: | |
return state; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment