0.0.4 • Published 2 years ago

my-react-global-states v0.0.4

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

My Global States is a simple javascript module that allows you to pass states from component to components in your React or React Native app without any complex configuration.

How to use?

  1. Install the package

    npm i my-react-global-states
  2. Create a js file anywhere in your app and you can name it any name you want. For this example I will name the file "globalStates.js" and I will place it under the folder "src". Inside globalStates.js you need to initialize the states' default value.

import {initState} from 'my-react-global-states';

export default initState({
    loading_screen: {
        show: false,
        message: null
    },
    user_info: null,
    product_list: []
})
  1. Once the default values are set, you need to call globalStates.js in the javascript entry point of your app.

React Native

import {AppRegistry} from 'react-native';
import App from './src';
import {name as appName} from './app.json';
import './src/globalStates'; // << add this

AppRegistry.registerComponent(appName, () => App);

React

You can call it under src/index.js

This will load the initial/default states when you launch your app.

METHODS

Listen to State Changes

import {stateListener} from 'my-react-global-states';
stateListener('loading_screen', (e) => {
        setLoadingParams(e);
});

Remove Listener

Note Always remove the listener on unmount when you plan to use the same listener on a different component.

import {removeStateListener} from 'my-react-global-states';

removeStateListener('loading_screen');

Update State

import {updateState} from 'my-react-global-states';

updateState('loading_screen', {
         show: true,
         message: 'hello world'
})

Get Specific State Value

import {getState} from 'my-react-global-states';

const myStates = getState('loading_screen');

Get All the States

import {getStates} from 'my-react-global-states';

const myStates = getState();

Initialize States

import {initState} from 'my-react-global-states';

export default initState({
    loading_screen: {
        show: false,
        message: null
    },
    user_info: null,
    product_list: []
})