-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
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>
);
};
Metadata
Metadata
Assignees
Labels
No labels