Created
February 14, 2021 06:15
-
-
Save Gosev/fbd960d5a653bf0f527678f038d5bee1 to your computer and use it in GitHub Desktop.
pages/jokes.tsx in NextJS : useEffect + useState + Axios
This file contains 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 * as React from 'react'; | |
import { useEffect, useState } from 'react'; | |
import axios from 'axios'; | |
const API = 'https://icanhazdadjoke.com/'; | |
const headers = {accept: 'application/json'}; | |
interface Joke { | |
id: string; | |
joke: string; | |
status: number; | |
} | |
const Jokes: React.FC<void> = () => { | |
const [joke, setJoke] = useState<string>(undefined); | |
const [counter, setCounter] = useState(0); | |
useEffect(() => { | |
axios.get<Joke>(API, {headers}) | |
.then((res) => { | |
// {id: "...", joke: "..", status: 200} | |
if (res.data.joke) setJoke(res.data.joke); | |
}); | |
}, [counter]); | |
return ( | |
<span style={{ fontSize:'2rem', fontWeight:'bold'}}> | |
{ joke ?? <>{joke}</>} | |
<br/> | |
<button onClick={() => setCounter(counter +1)}>Click me</button> | |
</span> | |
); | |
} | |
export default Jokes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment