Skip to content

Complex Local State Management (Non state form) #41

Description

@alacret

1. Problem

2. Current Solutions

3. Proposed Solutions

#41

Complex state management with multiples events with MixedEvent hook

import { createMixedEvent, useEvent } from '@cobuildlab/react-simple-state';

const initalState = { showModal: false, selectedItem: '' };

const OnSelectItem = createEvent({
  shared: true,
  reducer: (value: string, state) => ({
    ..state,
    selectedItem: value,
    showModal: true,
  }),
})

const OnCloseModal = createEvent({
  shared: true,
  reducer: (value: string, state) => ({
    ..state,
    selectedItem: value,
    showModal: true,
  }),
})

const actionsEvent = createMixedEvent({ SELECT: OnSelectItem, CLOSE: OnCloseModal, },{ initialValue: initalState, });

export const View = () => {
  const state = useEvent(actionsEvent);

  return (
    <>
      <button onClick={() => actionsEvent.events.SELECT.dispatch('item-id')}>Select item</button>
      <Modal isOpen={state.showModal} onClose={() => actionsEvent.events.CLOSE.dispatch()} />
    </>
  );
};

Other example

import { createEvent, createMixedEvent, useEvent, } from "@cobuildlab/react-simple-state";

const OnCallEnd = createEvent({
  shared: true,
  reducer: (value, prevState) => {
    return { ...prevState, state: "off", showCallWidget: false, number: null };
  },
});

const OnCallStart = createEvent({
  shared: true,
  reducer: (value, prevState) => {
    return {
      ...prevState,
      state: "calling",
      showCallWidget: true,
      number: value,
    };
  },
});

const OnCallUpdate = createEvent({
  shared: true,
  reducer: (value, prevState) => {
    return {
      ...prevState,
      data: value,
    };
  },
});
const initialState = {
  state: "off", // type of state 'off' 'calling' 'on-a-call',
  showCallWidget: false,
  number: null, // phone number to call
  data: {}, // call data
};

const callState = createMixedEvent(
  {
    UPDATE: OnCallUpdate,
    END: OnCallEnd,
    START: OnCallStart,
  },
  initialState
);
export const Calls = () => {
  const state = useEvent(callState);

  return (
    <div>
      <CallWidget
        isOpen={state.showCallWidget}
        number={state.number}
        callState={state.state}
      />
      <button onClick={() => callState.events.START.dispatch("456 677 6789")}>
        Start Call
      </button>
      <button onClick={() => callState.events.END.dispatch()}>End Call</button>
    </div>
  );
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions