Skip to content

Instantly share code, notes, and snippets.

@cjoecker
Created March 28, 2020 19:20
Show Gist options
  • Save cjoecker/06cfd1e91bf4d4846b01217c04b887c6 to your computer and use it in GitHub Desktop.
Save cjoecker/06cfd1e91bf4d4846b01217c04b887c6 to your computer and use it in GitHub Desktop.
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;
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}`}
});
})
};
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