Skip to content

Instantly share code, notes, and snippets.

@codewithgigi
Last active February 7, 2023 22:55
Show Gist options
  • Save codewithgigi/0ae1fcc684324618a822822e14988eaf to your computer and use it in GitHub Desktop.
Save codewithgigi/0ae1fcc684324618a822822e14988eaf to your computer and use it in GitHub Desktop.
React higher-order component example
// import React, { useState, useEffect } from "react";
const Pictures = ({ data }) => {
// const [data, setData] = useState(null);
// function fetchPicture() {
// const apiuri = "https://dog.ceo/api/breeds/image/random";
// fetch(apiuri)
// .then((response) => response.json())
// .then((apidata) => {
// setData(apidata);
// });
// }
// useEffect(() => {
// if (!data) fetchPicture();
// }, []);
return (
<div style={{ display: "flex", justifyContent: "center", marginTop: 10 }}>
{data ? (
<img src={data.message} width={400} />
) : (
<div
style={{
border: "1px solid lightgrey",
borderRadius: 5,
backgroundColor: "whitesmoke",
fontSize: 10,
textAlign: "center",
}}
>
{" "}
Loading ...
</div>
)}
</div>
);
};
export default Pictures;
//import React, { useState, useEffect } from "react";
const Quotes = ({data) => {
// const [data, setData] = useState(null);
// function fetchQuote() {
// const apiuri = "https://api.themotivate365.com/stoic-quote";
// fetch(apiuri)
// .then((response) => response.json())
// .then((apidata) => {
// setData(apidata);
// });
// }
// useEffect(() => {
// if (!data) fetchQuote();
// }, [
return (
<div style={{ display: "flex", justifyContent: "center", marginTop: 20 }}>
<div style={{ maxWidth: 600, textAlign: "center" }}>
{data?.quote ?? "Still trying to find a quote ..... 😔"}{" "}
<span style={{ fontSize: ".8rem" }}>{props?.data?.author ?? ""}</span>
</div>
</div>
);
};
export default Quotes;
import React, { useState, useEffect } from "react";
export const withFetch = (Component, fetchuri) => (props) => {
const [data, setData] = useState(null);
function fetchPicture() {
const apiuri = fetchuri;
fetch(apiuri)
.then((response) => response.json())
.then((apidata) => {
setData(apidata);
});
}
useEffect(() => {
if (!data) fetchPicture();
}, []);
return <Component {...props} data={data} />;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment