0.0.3 • Published 5 years ago

react-native-simple-global-state v0.0.3

Weekly downloads
2
License
ISC
Repository
github
Last release
5 years ago

Simple Global State for React Native

Alt text Alt text

Installation

npm i react-native-simple-global-state

Basic Usage

Firstly import StateProvider in your App.js

import {StateProvider} from 'react-native-simple-global-state';

Create initial state (obj)
For example increaseNumber There is the sipmle example for increase number.

 const App = () => {
  // first create initialState  obj.
  const initialState = {stateNumber: {number: 0}};
  // added reducer simple using state ,and actions
  const reducer = (state, action) => {
    switch (action.type) {
      case 'increaseNumber':
        return {
          ...state,
          stateNumber: action.increaseNumber,
        };
      // other case
      default:
        return state;
    }
  };
  return (
    // added Provider
    // given initialState and reducer in stateProvider.
    <StateProvider initialState={initialState} reducer={reducer}>
     ... 
    </StateProvider>
  );
};

How to use in component

First import useStateValue in your components

  import {useStateValue} from 'react-native-simple-global-state';

usage in component

  const MyButton = () => {
  const [{stateNumber}, dispatch] = useStateValue();
  //statenumber is your number, dispach for action.
  const onPress = () => {
    dispatch({
    // type=> action.type
      type: 'increaseNumber',
     // action
      increaseNumber: {number: stateNumber.number + 1},
    });
  };
  return (
    <TouchableOpacity onPress={onPress} >
      <Text>Press Me!</Text>
    </TouchableOpacity>
  );
};
export default MyButton;
import {useStateValue} from from 'react-native-simple-global-state';
const MyText = () => {
  const [{stateNumber}] = useStateValue();
  return (
    <View>
      <Text>{stateNumber.number}</Text>
    </View>
  );
};
export default MyText;