Search code examples
javascriptextjsextjs6

What is the best way to pass data from one app to another app


What is the best way to pass data from one app to another app.

I have a two extJS app lets called appA and appB.

In my appA I am using some of the views of appB. Therefore I need to pass some data to be passed.

what is the correct way to pass the data.

Currently I am using

var myOb= {"key1" : "value1","key2" : "value2"}

    sessionStorage.setItem('obJectData', muObj);

After use I am removing this like

sessionStorage.removeItem("obJectData");

Can anyone help me how and where to store the data in correct way.

I also have a though to be global vaiable.


Solution

  • If you need to have this across several different microapps all loaded on the same page, you might consider a combo approach of:

    1. A singleton that holds the current shared state items
    2. An events bus that can be used for pubsub (publish-subscribe) so that components/apps can subscribe to events and get updates when changes occur.

    A rudimentary example could be seen here:

    const appState = {
      count: 0,
    };
    
    const eventBus = {
      // just using the built-in DOM handlers, but you could create a custom one
      subscribe: (eventName, handler) => document.addEventListener(eventName, handler),
      publish: (eventName, payload) => document.dispatchEvent(new CustomEvent(eventName, payload)),
    };
    
    const incrementCount = () => {
      appState.count = appState.count + 1;
      eventBus.publish('newCount', { detail: { count: appState.count } });
    }
    
    const addCountDisplay = () => {
      const newDisplay = document.createElement('div');
      newDisplay.classList.add('countDisplay');
      newDisplay.textContent = appState.count;
      document.body.append(newDisplay);
    }
    
    // updateAllCountDisplays
    eventBus.subscribe('newCount', (e) => {
      const newCount = e.detail.count;
      const displays = document.querySelectorAll('.countDisplay');
      ([...displays]).forEach((display) => display.textContent = newCount.toString());
    });
    <button onclick="incrementCount()">increment count</button>
    <button onclick="addCountDisplay()">add count display</button>

    In this example, you can see that:

    1. Anytime you create a new count display, it is able to fetch the current count from the singleton appState
    2. Anytime you update the count, a custom event is triggered that is able to be subscribed to to update the UI in reaction to the change in state

    This could obviously be improved in many ways, but it serves as an example of how you can combine a globally available singleton in memory serving as a state cache with custom events to give all your components access to the current state as well as a way to subscribe and react to changes in state. This is not the only pattern you could use; it's just one option to consider.