Giter Site home page Giter Site logo

smirzo / vuex-observable-plugin Goto Github PK

View Code? Open in Web Editor NEW
10.0 2.0 2.0 1.14 MB

👁️ Plugin that adapts the popular redux-observable middleware to Vuex.

Home Page: https://redux-observable.js.org/

License: MIT License

JavaScript 95.62% HTML 1.55% Vue 2.83%
vue vuex vuex-plugin redux-observable vuex-observable

vuex-observable-plugin's Introduction

Vuex Observable

vuex-observable-image

A plugin that adapts the popular redux-observable middleware to Vuex.

CircleCI Coverage Downloads Version License

Please note that this plugin has not yet been battle tested in a production setting and should therefore be used with caution in a mission-critical environment.

Installation

npm i vuex-observable-plugin

Peer dependencies

npm i [email protected]

Your project should contain rxjs (version 6 or above) as redux-observable requires it as a peer dependency.

Usage

import Vue from 'vue';
import Vuex from 'vuex';
import { VuexObservable, ofType } from 'vuex-observable-plugin';

import { actions, mutations, state, getters, epics } from './store';

Vue.use(Vuex);

const store = new Vuex.Store({
  actions,
  mutations,
  state,
  getters,
  plugins: [VuexObservable(epics, { dependencies: { ofType } })],
});

Examples

Edit example

To see a working example you can check it out online on CodeSandbox or follow these simple instructions to run it locally.

API

VuexObservable(epics, options)

The main function that creates the plugin instance.

  • epics

    Description: An array containing all the epics.

    Type: Array

    Example: [someEpic, someOtherEpic]

  • options

    Description: Options passed to the observable middleware (mostly used for dependency injection). More info about the options can be found here.

    Type: Object

    Example: { dependencies: { http } }

ofType(actionType)

A helper operator for filtering the action stream by specific action type(s).

  • actionType

    Description: An action type string or an array of action type strings to filter the stream by. More info about this operator can be found here.

    Type: string | string[]

    Example: ofType('SOME_ACTION')

Differences between vuex-observable and redux-observable

This plugin aims to preserve the API of redux-observable and therefore most of the documentation is compliant with what is shown in the official redux-observable documentation.

There are however a couple of differences to the original API due to the inherent architectural difference between Vuex and Redux:

Epic's Outputs

By default, the epics receive an action as input and return a mutation as output. It is also possible to return an action as output by simply specifying a third action parameter in the returned object. For example:

(action$, store$, { ofType, mapTo }) =>
  action$.pipe(
    ofType('SOME_ACTION'),
    mapTo({ type: 'SOME_MUTATION' }),
  );

// => Triggers the mutation 'SOME_MUATATION'
(action$, store$, { ofType, mapTo }) =>
  action$.pipe(
    ofType('SOME_ACTION'),
    mapTo({ type: 'SOME_OTHER_ACTION', action: true }),
  );

// => Triggers the action 'SOME_OTHER_ACTION'

Store stream

The second argument passed to the epic is not only an observable of the state$ but the store$, which contains both the state and getters. For instance:

(action$, store$, { ofType, map }) =>
  action$.pipe(
    ofType('SOME_ACTION'),
    map(payload => ({
      type: 'SOME_MUTATION',
      payload: store$.value.state.number * store$.value.getters['COMPUTED_NUMBER'] * payload,
    })),
  );

Dispatching actions vs epics

A dispatched action is either passed to an action or an epic, but never to both at the same time.

Whenever an action with the dispatched type is available, it will be passed to the standard Vuex action handler with the matching type name and it will not reach the epics. However, when an action with the dispacthed type has not been registered, it will be passed on to be handled by the root epic.

This is because both actions and epics are usually asynchronous and running them both in parallel could often result in race conditions and unpredictable behaviour that is hard to test.

Performance related notes

When the state gets very large (thousands of object) or if state mutations happen extremely often, then the store might start suffering in performance. This is due to the state mutability differences between Vuex and Redux (Vuex's state is mutable while Redux's is not).

The plugin must therefore check if the state has actually changed on every dispatched epic and mutation in order to conform to the redux-observable api, which will expect a new object reference if the state has actually changed (so it can emit a new store stream event).

There could be ways to avoid this by editing the redux-observable source itself, but that would mean forgoing all the automatic bug fixes, testing and updates redux-observable already receives.

That being said, in most use cases this would never manifest as an issue.

Contributing

Any help with contributing, finding solutions or in general improving the library would be very welcome.

License

The MIT License (MIT)

Copyright (c) 2018 smirzo

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

vuex-observable-plugin's People

Contributors

dependabot[bot] avatar smirzo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vuex-observable-plugin's Issues

Greenkeeper activation

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Using with module-based store

Hi @smirzo,

Thanks for a great plugin! I'm struggling to make it work with module-based store, which I think is pretty common thing and is widely used as an approach for Vuex store architecture.
In the examples you are using strings in ofType calls. When using store modules I would love to have something like:

ofType(actions.START_STREAMING_NUMBERS.type)

instead of providing a string manually, for example (taken general is a store module name):

ofType('general/START_STREAMING_NUMBERS')

As far as I know those types are there out of the box when using Redux, but it's not the case for Vuex. Could you please advise, if it's even doable or there is no other way except mentioned above?

To make it at least not that ugly I'm using the following workaround (meh):

modules/general/index.js

export const moduleName = 'general';

modules/general/actions.js

import { moduleName } from './index';

const epicActionName = name => `${moduleName}/${name}`;

export const epicActionTypes = {
    START_STREAMING_NUMBERS: epicActionName('START_STREAMING_NUMBERS'),
    STOP_STREAMING_NUMBERS: epicActionName('STOP_STREAMING_NUMBERS'),
};

modules/general/epics.js

import { epicActionTypes } from './actions';
...
ofType(epicActionTypes.START_STREAMING_NUMBERS),
...

Many thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.