All Downloads are FREE. Search and download functionalities are using the official Maven repository.

hooks.state.ts Maven / Gradle / Ivy

There is a newer version: 0.80.3
Show newest version
import Settings from 'helpers/settings';
import React, { useEffect, useState } from 'react';
import { SetState } from 'types/react';
import Types, { Primitive } from 'types/types';

export type LocalState = {
  value: T,
  setValue: SetState
}

export const useLocalTypeState = (location: string, defaultValue:T): LocalState => {
  const [value, setValue] = useState(() => 
    Settings.read(
      location, 
      defaultValue
    )
  );

  useEffect(() => {
    Settings.write(location, value)
  }, [value])

  useEffect(() => {
    setValue(
      Settings.read(
        location, 
        defaultValue
      )
    )
  }, [location])

  return {value, setValue}
}
    
export const isCallback = (
  maybeFunction: any | ((...args: any[]) => void),
): maybeFunction is (...args: any[]) => void =>
  typeof maybeFunction === 'function'
  

export function useLocalState(location: string, defaultValue: S): [S, SetState] {
  const [value, setValue] = useState(() => Settings.read(location, defaultValue));

  useEffect(() => {
    Settings.write(location, value)
  }, [value])

  useEffect(() => {
    setValue(Settings.read(location, defaultValue))
  }, [location])

  return [value, setValue]
}

export const useSessionState = (location: string, defaultValue: any): any[] => {
  const [value, setValue] = useState(() => Settings.session.read(location, defaultValue));

  useEffect(() => {
    Settings.session.write(location, value)
  }, [value])

  return [value, setValue]
}