Skip to content

Instantly share code, notes, and snippets.

@rawnly
Created September 6, 2021 12:51
Show Gist options
  • Save rawnly/574e08f483e9133dc6af4337f19c951f to your computer and use it in GitHub Desktop.
Save rawnly/574e08f483e9133dc6af4337f19c951f to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react';
const useHistory = <T>( initialValue: T[] = [] ) => {
const [isDirty, setIsDirty] = useState( false );
const [step, setStep] = useState( 0 );
const [history, setHistory] = useState<T[]>( initialValue );
useEffect( () => {
console.log( {
isDirty,
step,
history
} )
}, [isDirty, step, history] )
function undo() {
if ( step <= 0 ) return;
console.log( 'UNDO' );
setStep( s => s - 1 )
setIsDirty( true )
}
function redo() {
if ( step >= history.length - 1 ) return;
console.log( 'REDO' );
setStep( s => s + 1 )
setIsDirty( s => s ? false : true )
}
function addStep( element: T ) {
console.log( 'ADD-STEP' );
if ( isDirty ) {
setHistory( h => [...h.slice( 0, step + 1 ), element] )
setIsDirty( false )
setStep( s => s + 1 )
return;
}
setHistory( data => [...data, element] )
setStep( s => s + 1 )
}
return {
undo,
redo,
addStep,
history,
step
}
}
export default useHistory;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment