JSPM

use-live-state

0.0.2
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 4
  • Score
    100M100P100Q25850F
  • License ISC

A react hook for LiveState

Package Exports

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (use-live-state) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    use-lives-state

    This package provides a lil tiny react hook to facilitate React components that have their state managed by LiveState.

    Usage

    Add it just like any npm:

    npm install use-live-state

    Make a LiveState instance:

    import LiveState from "phx-live-state";
    
    export const liveState = new LiveState('ws://localhost:4002/socket', 'todo:all');

    Then, in your components:

    import React, { Component } from 'react';
    import { liveState } from './live_state';
    import useLiveState from 'use-live-state';
    
    
    export const TodoList = () => {
    
      const [state, _pushEvent] = useLiveState(liveState, {});
    
      return (
        <ul>
          {(state as any).todos && (state as any).todos.map((todo) => <li>{todo}</li>)}
        </ul>
      );
    }
    import React, { Component, useRef } from 'react';
    import { liveState } from './live_state_react';
    import useLiveState from 'use-live-state';
    
    export const TodoForm = () => {
    
      const input = useRef(null);
    
      const [_state, pushEvent] = useLiveState(liveState, {});
    
      const onButtonClick = () => {
        pushEvent('add_todo', {todo: input.current.value});
        input.current.value = '';
      };
    
      return (
        <div>
          <input name="todo" ref={input} />
          <button onClick={onButtonClick}>Add Todo</button>
        </div>
      );
    }

    To see an example project of how all this fits together, check out https://github.com/launchscout/live_state/tree/main/testbed