DEV Community

Cover image for Always have plan B when your federated component fails
Ibrahim Shamma
Ibrahim Shamma

Posted on • Edited on

3 1 1 1 1

Always have plan B when your federated component fails

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

And that's it!

Your homework

  • Add a spinner that the host fails back into when waiting the component from the app1, (Use Suspense)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay