Skip to content

Instantly share code, notes, and snippets.

@rawnly
Last active May 26, 2022 15:50
Show Gist options
  • Save rawnly/60fa7ab91d4b3cdd53482e2c5b07fa3e to your computer and use it in GitHub Desktop.
Save rawnly/60fa7ab91d4b3cdd53482e2c5b07fa3e to your computer and use it in GitHub Desktop.
import { of, mergeMap, timer, concat } from 'rxjs'
import { useObservableState } from 'observable-hooks'
import { PropsWithChildren } from 'react'
// or whatever component you'd like to use
import { Button } from 'ariakit/button'
interface AutoResetButtonProps {
confirmText: string
timeout?: number
}
enum ButtonState {
IDLE,
SHOW_CONFIRM
}
const AutoResetButton: FC<PropsWithChildren<AutoResetButtonProps>> = ({
confirmText,
timeout = 1000,
...props
}) => {
const [state, setState] = useObservableState($b => $b.pipe(
mergeMap(s =>
concat(
of(s), // received value from `setState`
timer(timeout), // wait for $timeout
of(ButtonState.IDLE) // back to initial state
)
)
), ButtonState.IDLE);
const onButtonClick = useCallback(
function (e: any) {
if (state === ButtonState.IDLE) {
setState(ButtonState.SHOW_CONFIRM);
return;
}
props.onClick?.(e);
},
[props, setState, state]
);
return (
<Button {...props} onClick={onButtonClick}>
{state === 0 ? props.children : confirmText}
</Button>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment