Skip to content

timoj/react-pubsub-store

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React PubSub Store

Build Status

Introduction

This is a implementation of a pubsub pattern for React. You can subscribe on store names that you create. When you subscribe to a store name that doesn't exist yet, it will be created as well as a initial data fetch for the specific store.

Installation

npm install --save react-pubsub-store

You need to create a component that implements a functions fetchResource and setResource, which you will pass to the pubsub store. For example:

var Fetcher = (function () {

    .....

    return {
        fetchResource: function (path, cb) {
            fetch(url, {
                method: 'GET',
            }).then(response => response.json())
            .then(response => cb(response));
        },
        setResource: function (path, data, cb) {
            fetch(url, {
                method: 'POST',
                ...
            }).then(response => response.json())
            .then(response => cb(response));
        }
    };
})();

export default Fetcher;
....

ReactPubSubStore.setDAO(Fetcher);

You can now start a new subscription:

this.subscription = ReactPubSubStore.subscribe('storeName', function (obj) {
  console.log("Just got data for the store 'storeName': ", obj);
});

and you can publish new data:

ReactPubSubStore.publish('storeName', data);

Don't forget to unsubscribe when the component unmounts:

componentWillUnmount() {
    this.subscription.remove();
}

About

A Simple React pubsub store implementation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published