Git Product home page Git Product logo

react-livedata's Introduction

React with ViewModels and LiveData

This lightweight module will allow for MVVM architecture development inside of the React Framework. This was designed to work with create-react-app.

The architecture was inspired by benefits seen in the native Android development environment with Viewmodels/LiveData.

Getting Started

npm install --save react-livedata 

Skip to example section below for code implementation.

Your JS Viewmodel class can extend the ViewModel. Your Viewmodel's constructor needs to be called with the react component whose state we are modeling. Your react component will create a reference to your viewmodel. That reference can be used throughout the lifecycle of the component, i.e. inside the component's render method.

In your tests you can create your same ViewModel class with a mocked react component using the ReactStateComponentMock.

Minimum code boiler plate for ViewModel:

import ViewModel, { LiveData } from 'react-livedata';

export const liveData = Object.freeze({
    myLiveData: new LiveData('initval'),
});

export default class MyFormViewModel extends ViewModel {
    constructor(reactObj) {
        super(reactObj, liveData);
    }
}

Example

ViewModel: MyFormViewModel.js

import ViewModel, { LiveData } from 'react-livedata';
//declare your livedata properties and initial/default property values here
export const liveData = Object.freeze({
    myLiveDataLabel: new LiveData('Initial string value of my live data', 'optionalKeyNameForDebugging'),
    myLiveDataWithNoOptionalPropertyName: new LiveData(0)
});

export default class MyFormViewModel extends ViewModel {
    constructor(reactObj, injectedLocalStorageDepencency) {
        super(reactObj, liveData);
        this.localStorageDependency = injectedLocalStorageDepencency;
    }

    onSubmitClicked() {
        this.setLiveData(liveData.myLiveDataLabel, 'modified value');
        if(this.getLiveData(liveData.myLiveDataLabel) === 'Initial string value of my live data') {
            console.log('this wont print becuase you updated :)')
        }
        this.localStorageDependency.setItem('someLocalStorageKey', 'Some Local Storage Value'); //showing off injection of dependencies here
    }

    someOtherMethod() {
        //if you need the value of your optionalKeyNameForDebugging, you can use the js Symbol API:
        //Example: key/value from local storage:
        let restorationValue = this.localStorageDependency.getItem(liveData.myLiveDataLabel.key.description);
    }
}

React Component

import React from 'react';
import MyFormViewModel, { liveData } from './MyFormViewModel';

class MyComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {};
        this.myFormViewModel = new MyFormViewModel(this, localStorage);
    }

    render() {
        return(<>
            <div>{this.state[liveData.myLiveDataLabel]}</div>
            <Button onClick={()=>{this.myFormViewModel.onSubmitClicked()}} >
        </>);
    }
     
}

Tests

Using the react-scripts test, you can mock out all dependencies and inject them into your ViewModel.

import { ReactStateComponentMock } from 'react-livedata';
import MyFormViewModel, { liveData } from './MyFormViewModel';
test('FormViewModel Example Test', async () => {
    //Mock your dependency
    class LocalStorageProviderMock extends LocalStorageProvider {
        constructor() {
            super()
            this.localStorage = {};
        }

        getItem(key) {
            return this.localStorage[key];
        }
        
        setItem(key, value) {
            this.localStorage[key] = value;
        }
    }
    
    const formViewModel = new MyFormViewModel(new ReactStateComponentMock(), new LocalStorageProviderMock());
    expect(formViewModel.getLiveData(liveData.myLiveDataLabel)).toBe('Initial string value of my live data');
    
    //click submit (mocking user interactions)
    formViewModel.onSubmitClicked();
    expect(formViewModel.getLiveData(liveData.myLiveDataLabel)).toBe('modified value');
});

Pros

  • Faster test times: No browser (headless or otherwise) needed to run tests.
  • Business logic can be taken out of the view layer and relocated into a dependency-injectable, testable class.

Cons

  • Initial properties based on variables need to be set in the constructor, away from the declaration. For Example:
constructor(reactObj, injectedDepencency) {
    super(reactObj, liveData);
    const conf = getConfig();
    this.setLiveData(liveData.myLiveDataLabel, conf.someConfigRelatedValue);
}
  • A little wordy on imports and get/set statements.

react-livedata's People

Contributors

jeffski13 avatar

Watchers

 avatar

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.