What I am trying to do:
- fetch data in useEffect from my component
- update loading state from the HOC
- return wrapped component /display data
App.js
import axios from "axios";
import { useEffect, useState } from "react";
import withFetch from "./withFetch";
const App = ({ setLoading }) => {
const [data, setData] = useState([]);
useEffect(() => {
setLoading(true);
async function fetchData() {
await axios
.get("https://jsonplaceholder.typicode.com/todos")
.then((res) => {
setData(res.data);
setLoading(false);
});
}
fetchData();
}, []);
return (
<div>
{data.map((item) => (
<p>{item}</p>
))}
</div>
);
};
export default withFetch(App);
withFetch /HOC:
import React, { useState } from "react";
const withFetch = (WrappedComponent) => {
const WithFetch = (props) => {
const [isLoading, setLoading] = useState(false);
if (isLoading) return <h1>Loading..</h1>;
return <WrappedComponent setLoading={setLoading} {...props} />;
};
return WithFetch;
};
export default withFetch;
What goes wrong:
- infinite loop from/to HOC and my component
I made a very simple demo in CodeSandbox to demonstrate my problem: https://codesandbox.io/s/reverent-cache-bb044?file=/src/App.js