Coder Social home page Coder Social logo

redux-persist-crosstab's Introduction

Redux Persist Crosstab

Add cross tab syncing to your redux app with 1 line. This tiny module listens to the window for redux-persist storage events. When an event occurs it will dispatch a rehydrate action.

Usage

import { createStore, compose } from 'redux'
import { persistStore, autoRehydrate } from 'redux-persist'
import crosstabSync from 'redux-persist-crosstab'
const finalCreateStore = compose(autoRehydrate())(createStore)
const store = finalCreateStore(reducer)

const persistor = persistStore(store, {})
crosstabSync(persistor)

To blacklist some portion of state, for example if you want to avoid syncing route state:

crosstabSync(persistor, {blacklist: ['routeReducerKey']})

Rehydration Merge

Redux Persist does a shallow merge of state during rehydration. This means that if state changes on two tabs simulataneously, it is possible that legitimate state will be lost in the merge. In most cases this will not be an issue. One scenario where this could happen is if both tabs are listening on a socket and they both receive a message at the same time. If you have this type of set up you will either need to blacklist the relevant reducers or implement a custom rehydration handler that takes into account the nuances of this situation.

redux-persist-crosstab's People

Contributors

aij avatar cephirothdy2j avatar irisschaffer avatar rt2zz avatar tsmmark avatar vladtsf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redux-persist-crosstab's Issues

Issue using with redux-persist on REHYDRATE action type.

I am using both redux-persist and redux-persist-crosstab and the reducers return the Initial State of the application when action type is REHYDRATE for handling the corrupt state.

const reducer1 = (state=INITIAL_STATE.reducer1, action) => {
        case REHYDRATE:
            return INITIAL_STATE;

        default:
            return state;
    }
}

Now crosstab overlaps with it because even crosstab uses REHYDRATE action - So, whenever I open a new tab, the initial state is returned and not the updated state from other tabs.
persistor.rehydrate(statePartial, {serial: true})

What to do in such a case?

Endless loop

handleStorageEvent will be endless loop when the count of tab is more than two

Unable to serialise

I'm getting errors using this with redux-persist 2.0 as persistor.rehydrate is being passed an object instead of a string, which causes the deserialise function to die. My workaround has been to parse the newValue value, then stringify the whole statePartial object:

statePartial[keyspace] = JSON.parse(e.newValue); persistor.rehydrate(JSON.stringify(statePartial), function(){ //@TODO handle errors? })

Crosstab and Fields problem?

i'm working on a project based on redux. I have pages for adding new applications, roles, companies etc. And they have some fields inside. I'm using redux-persist for persistence on localStorage. Also using crosstabSync for multiple tab store sync.

Now the problem is that sync system mess with rehydration. When i click to add new company button and arrive to:
http://localhost:3000/ui/company/-1
persist/Rehydrate starts to action for multiple/endless time. My application page code:

import React from 'react';
import { connect } from 'react-redux';
import BaseContainer from '../../shared/BaseContainer';
import { Form, Input, Col, Checkbox, Card, Spin, Row } from 'antd';
import { loadCompany, unloadCompany, saveCompany, newCompany } from './CompanyActions';
import { hasPermission } from '../../../utils/Authentication';
const FormItem = Form.Item;

class CompanyForm extends BaseContainer {

componentDidMount() {
    if (this.props.match.params.id === "-1") {
        this.props.dispatch(newCompany());
    } else {
        this.props.dispatch(loadCompany(this.props.match.params.id));
    }
}

componentWillUnmount() {
    this.props.dispatch(unloadCompany());
}

handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
        if (!err) {
            values.id = this.props.company.id;
            this.props.dispatch(saveCompany(values));
        }
    });
}

render() {
    if (this.props.loading === undefined || this.props.loading) {
        return <div className="centerOfPage"><Spin size="large"/></div>
    }
    const { getFieldDecorator } = this.props.form;
    return <span>
        <div className="mt2"/>
        <Card className="mt1" title={this.getFormTitle(this.props.company.id, this.props.company.name, hasPermission("companies:save"))}>
          <Form layout="vertical">
            <Row gutter={16}>
            <Col xs={24} sm={12} md={12}  lg={6} xl={6} className="gutter-row">
                <FormItem
                    label="Name"
                    hasFeedback
                    >
                    {getFieldDecorator('name', {
                        rules: [
                            {required: true, message: 'Please Enter Company Name'}],
                    })(
                        <Input placeholder="Name"/>
                    )}
                </FormItem>
            </Col>
            <Col xs={24} sm={12} md={12}  lg={6} xl={6} className="gutter-row">
                <FormItem
                    label="Description"
                    hasFeedback
                    >
                    {getFieldDecorator('description', {
                        rules: [
                            {required: true, message: 'Please Enter Description'}],
                    })(
                        <Input placeholder="Description"/>
                    )}
                </FormItem>
            </Col>
            <Col xs={24} sm={12} md={12} lg={6} xl={6} className="gutter-row">
            <FormItem
                label="Enabled"
                >
                {getFieldDecorator('enabled', {
                    valuePropName: 'checked'
                })(
                    <Checkbox/>
                )}
            </FormItem>
        </Col>
        </Row>
        </Form>
        </Card>
    </span>
}

}

const mapPropsToFields=(props)=>{
    let company = props.company;
    if (company === undefined) {
        company = {};
    }
return {
    description:  { value: company.description },
    name: { value : company.name},
    enabled : { value : company.enabled },
    id : { value : company.id }
    };
};

const mapStateToProps = (state) => ({
    company: state.companies.company,
    loading : state.companies.loading
});
const Company = Form.create({mapPropsToFields})(CompanyForm);

export default connect(
  mapStateToProps
)(Company);

Loop cause mainly "mapPropsToFields" part. It returns allways in that.

So i tried adding

   const mapPropsToFields=(props)=>{
 if ( filledValues ) {
   let company = props.company;
   if (company === undefined) {
       company = {};
   } return {...

Also i'm changing:

  componentDidMount() {
    if (this.props.match.params.id === "-1") {
        this.props.dispatch(newCompany());
      filledValues = true;
    } else {
        this.props.dispatch(loadCompany(this.props.match.params.id));
      filledValues = true;
    }
}

So after dispatch part completed that state starts to action right. But why that happens and is that the right way to do?

If necessary this is the reducer part of company:

case CompanyActions.NEW_COMPANY :
  return Object.assign({}, state, {
    company: {},
    loading : false
  });

And also i have to edit bec it's not working when you try to edit company. Fields empty. And when i refresh page on add company i found that crosstabSync restarts itself.

@rt2zz Do you have any idea?

Whitelist support

Was about to request whitelist support in the parent project, but @grabbou beat me to it :)

In the linked issue you said:

My hesitation is that I have yet to see an app that would whitelist more than it would blacklist.

I think it's the opposite in this case, since cross-tab syncing is so sensitive to race conditions (at least with the current implementation). Mimicking redux-persist in this matter is the obvious solution.

Local storage on multiple dispatches to state updates, causes inconsistency in data

Right now I am facing the issue where I have to update multiple reducers one after other. This creates inconsistency in the local storage.

How inconsistency is happening:

  • Suppose we have multiple dispatches are lined up.
  • After 1st dispatch and state update, the data is stored in the local storage which triggers storage event.
  • Now this update triggers another storage event, which is okay if something didn't change on the tab which initiated the 1st dispatch and things work out properly.
  • But most of the times due to async nature of dispatch and storage events the data ends up in a bad shape.

I was thinking that if I would have a function that I would call to actually flush the data to the storage, so the event only triggers once with the complete set of updated data.

Or is there some better solution that already exists for this, maybe to batch the dispatches for state updates across multiple reducers and put the data at once in the local storage?

Crosstab action flag

in this blob of code

  var statePartial = {}

  statePartial[keyspace] = e.newValue

  persistor.rehydrate(statePartial, {serial: true})

it would be nice if there could be configured a flag or blob to be added to the statePartial so that cross tab rehydrates could be differentiated from page load rehydrates i.e.

if(showFlag){ statePartial._CROSSTAB_REHYDRATE_ = true }

or something like that

Why not middleware?

What it the benefit of implementing such functionality at the Redux-Persist level vs as Redux middleware (ie. like with redux-state-sync)?

Only one I can think of is that as it's dependent on Redux-Persist, so all app instances are starting with latest state.

When similar functionality is implemented as middleware, only single actions are synced. Using this module whole state is being retrieved and hydrated.

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.