EventsReceiver

Attribute name

Type

Description

eventNames

string | string[]

Event name or array of event names

receiver

(eventName: string, eventData: any, stateManager: StateManager):void | Promise<any>

This function will be called when one of required events will be called.

EventsReceiver can handle one or more events. Thats mean when You emit some event. Eventrix will invoked receiver when event name match to his events list.

import { EventsReceiver } from 'eventrix';

const removeUserReceiver = new EventsReceiver(
    'Users:remove.user',
    (eventName, eventData, stateManager) => {
        const usersList = stateManager.getState('users');
        const newUsersList = usersList.filter(user => user.id !== eventData.id);
        stateManager.setState('users', newUsersList);
    }
);

export default removeUserReceiver;

You can also listen on list of events and check which event was emitted.

import { EventsReceiver } from 'eventrix';

const usersReceiver = new EventsReceiver(
    ['Users:add.user', 'Users:remove.user'],
    (eventName, eventData, stateManager) => {
        const usersList = stateManager.getState('users');
        if (eventName === 'Users:add.user') {
            stateManager.setState('users', [...usersList, eventData]);
        }
        if (eventName === 'Users:remove.user') {
            const newUsersList = usersList.filter(user => user.id !== eventData.id);
            stateManager.setState('users', newUsersList);
        }
    }
);

export default usersReceiver;

When You need handle some async action You can return Promise. If receiver return Promise then Eventrix wait for Promise resolve and You can handle state change when Promise resolved.

import { EventsReceiver } from 'eventrix';
import axios from 'axios';

const createUserReceiver = new EventsReceiver(
    'Users:create.user',
    (eventName, eventData, stateManager) => {
        return axios.post(`http://users.com/users`, eventData)
             .then((response) => {
                 const newUser = response.data;
                 const usersList = stateManager.getState('users');
                 stateManager.setState('users', [...usersList, newUser]);
             });
    }
);

export default createUserReceiver;

Complete example how use EventsReceiver

import { EventsReceiver, Eventrix } from 'eventrix';

const initialState = {
    users: [],
};

const removeUserReceiver = new EventsReceiver(
    'Users:remove.user',
    (eventName, eventData, stateManager) => {
        const usersList = stateManager.getState('users');
        const newUsersList = usersList.filter(user => user.id !== eventData.id);
        stateManager.setState('users', newUsersList);
    }
);

const receivers = [removeUserReceiver];

const eventrix = new Eventrix(initialState, receivers);

export default eventrix;

You can register EventsReceiver later by:

eventrix.useReceiver(createUserReceiver);

or remove receiver by:

eventrix.removeReceiver(createUserReceiver);

Last updated