Created
February 8, 2019 16:34
-
-
Save pdewouters/92af5d06f95fa201edf5b3c19809661b to your computer and use it in GitHub Desktop.
Fetch from API with useEffect
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 React, { useState, useEffect } from "react"; | |
export default function QuoteBox() { | |
const API_URL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1"; | |
const [quote, setQuote] = useState({}); | |
const [isLoading, setLoading] = useState(false); | |
async function queryAPI() { | |
setLoading(true); | |
const response = await fetch(API_URL); | |
const [quote] = await response.json(); | |
setQuote(quote); | |
setLoading(false); | |
} | |
const handleButtonClick = () => queryAPI(); | |
useEffect(() => { | |
queryAPI(); | |
}, []); | |
return ( | |
<> | |
<figure class="quote" id="quotebox"> | |
{ isLoading ? 'Loading' : | |
<> | |
<blockquote dangerouslySetInnerHTML={{__html: quote.content}}></blockquote> | |
<figcaption>{quote.title}</figcaption> | |
</> | |
} | |
</figure> | |
<button onClick={handleButtonClick}>Change quote</button> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment