npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fusion-plugin-universal-events-react

v2.2.1

Published

React Provider and HOC for Fusion universal-events

Downloads

352

Readme

fusion-plugin-universal-events-react

Build status

The fusion-plugin-universal-events-react is a drop-in replacement for UniversalEventsToken from the fusion-plugin-universal-events. It can be used as a dependency by other Fusion.js plugins and works as an event emitter for data such as statistics and analytics. This plugin captures events emitted from the client, sends them in batches to the server periodically, and allows the server to handle them. Note that due to the batched and fire-and-forget nature of the client-to-server event emission, this library is not suitable for timing-sensitive requests such as error logging or RPC calls.

This plugin also installs a React provider component at the top of the React tree and exports a higher order component that exposes the event emitter to component props.

This plugin is useful for when you want to collect data about user actions or other metrics, and send them in bulk to the server to minimize the number of HTTP requests.

For convenience, this plugin automatically flushes its queue on page unload.


Table of contents


Installation

yarn add fusion-plugin-universal-events-react

Usage

import {withBatchEvents} from 'fusion-plugin-universal-events-react';

const Component = ({universalEvents}) => {
  universalEvents.on('foo', payload => {
    console.log(payload);
  });
};

export default withBatchEvents(Component);

Setup

// main.js
import React from 'react';
import App from 'fusion-react';
import UniversalEvents, {
  UniversalEventsToken,
} from 'fusion-plugin-universal-events-react';
import {FetchToken} from 'fusion-tokens';

export default function() {
  const app = new App();
  app.register(UniversalEventsToken, UniversalEvents);
  __BROWSER__ && app.register(FetchToken, window.fetch);
  return app;
}

API

Registration API

UniversalEvents
import UniversalEvents from 'fusion-plugin-universal-events';

The plugin. Provides the service API. Typically should be registered to UniversalEventsToken.

Dependencies

FetchToken
import {FetchToken} from 'fusion-tokens';
// ...
__BROWSER__ && app.register(FetchToken, window.fetch);

Required. Browser-only. See https://github.com/fusionjs/fusionjs/tree/master/fusion-tokens#fetchtoken


Service API

events.on

Registers a callback to be called when an event of a type is emitted. Note that the callback will not be called if the event is emitted before the callback is registered.

events.on((type: string), (callback: (payload: Object, ctx: ?Context) => void));
  • type: string - Required. The type of event to listen on. The type * denotes all events.
  • callback: (mappedPayload: Object, ctx: ?Context) => void - Required. Runs when an event of matching type occurs. Receives the payload after it has been transformed by mapper functions, as well an optional ctx object.
events.emit
events.emit((type: string), (payload: Object));
  • type: string - Required. The type of event to emit. The type * denotes all events.
  • payload: Object - Optional. Data to be passed to event handlers
events.map

Mutates the payload. Useful if you need to modify the payload to include metrics or other meta data.

events.map(
  (type: string),
  (callback: (payload: Object, ctx: ?Context) => Object)
);
  • type: string - Required. The type of event to listen on. The type * denotes all events.
  • callback: (payload: Object, ctx: ?Context) => Object - Required. Runs when an event of matching type occurs. Should return a modified payload
events.flush

Flushes the data queue to the server immediately. Does not affect flush frequency

events.flush();
events.setFrequency
events.setFrequency((frequency: number));

Sets the frequency at which data is flushed to the server. Resets the interval timer.

  • frequency: number - Required.
events.teardown
events.teardown();

Stops the interval timer, clears the data queue and prevents any further data from being flushed to the server. Useful for testing

events.from
const scoped = events.from((ctx: Context));

Returns a scoped version of the events api.

withBatchEvents

import {withBatchEvents} from 'fusion-plugin-universal-events-react';

const Component = ({universalEvents}) => {
  universalEvents.on('foo', payload => {
    console.log(payload);
  });
};

export default withBatchEvents(Component);

Other examples

Event transformation

It's possible to transform event data with a mapping function, for example to attach a timestamp to all actions of a type.

events.map('user-action', payload => {
  return {...payload, time: new Date().getTime()};
});

events.on('user-action', payload => {
  console.log(payload); // logs {type: 'click', time: someTimestamp}
});

events.emit('user-action', {type: 'click'});

Accessing ctx

Event mappers and handlers take an optional second parameter ctx. For example:

events.on('type', (payload, ctx) => {
  //...
});

This parameter will be present when events are emitted from the ctx scoped EventsEmitter instance. For example:

app.middleware({events: UniversalEventsToken}, ({events}) => {
  events.on('some-scoped-event', (payload, ctx) => {});
  return (ctx, next) => {
    const scoped = events.from(ctx);
    scoped.emit('some-scoped-event', {some: 'payload'});
  };
});

* event type

* is a special event type which denotes all events. This allows you to add a mapper or handler to all events. For example:

events.map('*', payload => {
  //
});