Skip to content

Instantly share code, notes, and snippets.

@pdewouters
Created February 8, 2019 16:34
Show Gist options
  • Save pdewouters/92af5d06f95fa201edf5b3c19809661b to your computer and use it in GitHub Desktop.
Save pdewouters/92af5d06f95fa201edf5b3c19809661b to your computer and use it in GitHub Desktop.
Fetch from API with useEffect
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