I created a Higher Order Component (HOC) or Container component from where I am fetching data and sending to child component. I am also using React-Router-DOM library for routing.
I am using HOC component like this:
<BrowserRouter>
<Routes>
<Route path={'/'} element={<HOC Component={App} />} />
</Routes>
</BrowserRouter>
I am sending data to child component like this:
export const HOC = ({ Component }) => {
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = {
message:
'Data fetched successfully' + Math.floor(Math.random() * 100),
};
return resolve(data);
}, 2000); // Simulating a delay of 2 seconds
});
};
return (
<div>
<If condition={fetchData()}>
<Fallback>Loading data ...</Fallback>
<Then>
{(data) => (
<>
<span>parent component your data:{JSON.stringify(data)}</span>
<Component data={data} />
</>
)}
</Then>
<Else>{(error) => <span>Failed to load data because </span>}</Else>
</If>
</div>
);
};
Now issue is that there is an CTA in my child component, on click of that I want to fetch again data. Is there any way using React-Router-DOM? I want to re-render HOC so that it fetch again and send new data to child component.
Here is my code:
One way I am think to pass fetchData
to child component and do the manipulation but I don’t think parent component have correct data.
2
Answers
// hoc.tsx file
// App.tsx file
You might be able to accomplish this via the RRD router, but you’d need to use one of the Data routers and a route loader/action and you’d likely need to refactor much of your logic to work with the loader/action. This is probably a much heavier lift than it needs to be or for what you are looking to do. My suggestion would be to just pass
fetchData
down as a prop along with the fetcheddata
, to the component you are decorating.Update your "HOC" to be a true Higher Order Component, and decorate the
App
component export.hoc.tsx
fetchData
callback as props.If
–Then
–Else
in the non-loading branch.App.tsx
App
component.main.tsx
Render the
App
component normally on a route.