I am trying to use an HOC component in React with a functional component, but when using hooks I keep getting the error React Hook "useEffect" cannot be called inside a callback.
What am I doing wrong and how can I solve this?
const HOC = (WrappedComponenet, entity) => {
return function () {
const [data, setData] = useState([]);
const [term, setTerm] = useState("");
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/${entity}`)
.then((res) => res.json())
.then((data) => setData(data));
}, []);
let filteredData = data.slice(0, 10).filter((d) => {
if (entity === "users") {
const { name } = d;
return name.indexOf(term) >= 0;
}
if (entity === "todos") {
const { title } = d;
return title.indexOf(term) >= 0;
}
});
return <WrappedComponenet data={filteredData} />;
};
};
Check out this snippet:
const HOC = (WrappedComponenet, entity) => {
function MyCustomComponent() {
const [data, setData] = useState([]);
const [term, setTerm] = useState("");
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/${entity}`)
.then((res) => res.json())
.then((data) => setData(data));
}, []);
let filteredData = data.slice(0, 10).filter((d) => {
if (entity === "users") {
const { name } = d;
return name.indexOf(term) >= 0;
}
if (entity === "todos") {
const { title } = d;
return title.indexOf(term) >= 0;
}
});
return <WrappedComponenet data={filteredData} />;
};
return <MyCustomComponent/>
};