Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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