You are now used to the following code:
import React from "react";
const App1 = React.lazy(() => import("app1/App"));
function App() {
return (
<>
<App1 />
<div className="App">host</div>
</>
);
}
export default App;
But what if the host
could not load the app1
?
what if app1
site is down?
In these cases you will have the house of cards falls all over the place, meaning if single microfrontend fails in a page the entire page will throw an error.
We can agree that this is not the best solution, but what can we do in this case?
When you federate a component, you need to have a fallback component
Maybe you're thinking of suspense? but suspense is designed for components that will eventually be loaded rather than components that fails, what we need specifically is an ErrorBoundary
Checkout the code here:
// app1-wrapper.tsx
import { Suspense, Component } from 'react';
const App1 = React.lazy(() => import("app1/App"));
class App1Wrapper extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <div>Our plan B for app1</div>
}
return <App1/>
}
}
export default App1Wrapper;
NOTE: the error boundary currently only supported on class based components
Now you import your wrapper safely inside your Host app.tsx
import React from "react";
import App1 from './app1-wrapper'
function App() {
return (
<>
<App1 />
<div className="App">host</div>
</>
);
}
export default App;
And that's it!
Your homework
- Add a spinner that the host fails back into when waiting the component from the
app1
, (Use Suspense)
Top comments (0)