2

I need to send data from one LWC to another on a community, both the lwcs are in a dedicated community page

  • Are you expecting the two community pages to be open in different browser windows (in the same browser session) at the same time, or are you trying to pass data from one page to another? If the latter you need to consider creating URLs that include query parameters from which the components fetch necessary information. – Phil W Apr 20 at 14:43
4

@Teemo_smr It seems you are looking for communication between different pages not on the same page. The below lines from the link seems to be able to do it.

Use a Lightning Message Channel (Beta) To communicate between components within a single Lightning page or across multiple pages, you can use a Lightning message channel. The advantage of using a Lightning message channel over pubsub is that message channels are not restricted to a single page. Any component in a Lightning Experience application that listens for events on a message channel updates when it receives a message. It works between Lightning web components, Aura components, and Visualforce pages in any tab or in any pop-out window in Lightning Experience. It also works across namespaces. For more information, see Communicate Across the DOM with Lightning Message Service (Beta).

| improve this answer | |
0

Communicating between two Lightning Web Components that are not contained in the same DOM tree can be done using the pubsub module that Salesforce has provided. This works familiarly to application events in Aura. Refer to the "Communicate Between Components" page in the LWC Dev Guide. Relevant excerpt:

Use the pubsub Module To communicate between components on a single page, you can use the pubsub module.

In a publish-subscribe pattern, one component publishes an event. Other components subscribe to receive and handle the event. Every component that subscribes to the event receives the event. For example, if you add two components to a Lightning page in Lightning App Builder, use the pubsub module to send events between them. The pubsub module restricts events to a single page.

In the doc Salesforce recommends copying the pubsub module from the lwc-recipes repo.

Code for pubsub.js below in case the GitHub repo disappears for any reason:

/**
 * A basic pub-sub mechanism for sibling component communication
 *
 * TODO - adopt standard flexipage sibling communication mechanism when it's available.
 */

const events = {};

/**
 * Confirm that two page references have the same attributes
 * @param {object} pageRef1 - The first page reference
 * @param {object} pageRef2 - The second page reference
 */
const samePageRef = (pageRef1, pageRef2) => {
    const obj1 = pageRef1.attributes;
    const obj2 = pageRef2.attributes;
    return Object.keys(obj1)
        .concat(Object.keys(obj2))
        .every((key) => {
            return obj1[key] === obj2[key];
        });
};

/**
 * Registers a callback for an event
 * @param {string} eventName - Name of the event to listen for.
 * @param {function} callback - Function to invoke when said event is fired.
 * @param {object} thisArg - The value to be passed as the this parameter to the callback function is bound.
 */
const registerListener = (eventName, callback, thisArg) => {
    // Checking that the listener has a pageRef property. We rely on that property for filtering purpose in fireEvent()
    if (!thisArg.pageRef) {
        throw new Error(
            'pubsub listeners need a "@wire(CurrentPageReference) pageRef" property'
        );
    }

    if (!events[eventName]) {
        events[eventName] = [];
    }
    const duplicate = events[eventName].find((listener) => {
        return listener.callback === callback && listener.thisArg === thisArg;
    });
    if (!duplicate) {
        events[eventName].push({ callback, thisArg });
    }
};

/**
 * Unregisters a callback for an event
 * @param {string} eventName - Name of the event to unregister from.
 * @param {function} callback - Function to unregister.
 * @param {object} thisArg - The value to be passed as the this parameter to the callback function is bound.
 */
const unregisterListener = (eventName, callback, thisArg) => {
    if (events[eventName]) {
        events[eventName] = events[eventName].filter(
            (listener) =>
                listener.callback !== callback || listener.thisArg !== thisArg
        );
    }
};

/**
 * Unregisters all event listeners bound to an object.
 * @param {object} thisArg - All the callbacks bound to this object will be removed.
 */
const unregisterAllListeners = (thisArg) => {
    Object.keys(events).forEach((eventName) => {
        events[eventName] = events[eventName].filter(
            (listener) => listener.thisArg !== thisArg
        );
    });
};

/**
 * Fires an event to listeners.
 * @param {object} pageRef - Reference of the page that represents the event scope.
 * @param {string} eventName - Name of the event to fire.
 * @param {*} payload - Payload of the event to fire.
 */
const fireEvent = (pageRef, eventName, payload) => {
    if (events[eventName]) {
        const listeners = events[eventName];
        listeners.forEach((listener) => {
            if (samePageRef(pageRef, listener.thisArg.pageRef)) {
                try {
                    listener.callback.call(listener.thisArg, payload);
                } catch (error) {
                    // fail silently
                }
            }
        });
    }
};

export {
    registerListener,
    unregisterListener,
    unregisterAllListeners,
    fireEvent
};
| improve this answer | |
  • 1
    this is used only for components that are in the same page, I need to comunicate between component that are in different pages – Teemo_smr Apr 20 at 14:14
  • Sorry for missing that. If that's the case Platform Events is likely the best way to have the two components react to events. – nbrown Apr 20 at 14:19
  • Worth also noting that pubsub doesn't work if the components are in different namespaces. – Phil W Apr 20 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.