Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Created February 26, 2018 00:44
Show Gist options
  • Save treyhuffine/fdc49adbf509a064db751d54f274ca27 to your computer and use it in GitHub Desktop.
Save treyhuffine/fdc49adbf509a064db751d54f274ca27 to your computer and use it in GitHub Desktop.
An educational time travel implementation for Redux
const timeline = [];
let activeItem = 0;
const saveTimeline = () => {
timeline.push(store.getState());
timelineNode.innerHTML = timeline
.map(item => JSON.stringify(item))
.join('<br/>');
activeItem = timeline.length - 1;
};
store.subscribe(saveTimeline);
// FOR DEBUGGING & EDUCATIONAL PURPOSES ONLY
// The store should not be extended like this.
store.setState = desiredState => {
store.state = desiredState;
// Assume the debugger is injected last. We don't want to update
// the saved states as we're debugging.
const applicationListeners = store.listeners.slice(0, -1);
applicationListeners.forEach(listener => listener());
};
// This assumes there are previous/next buttons with the give IDs to control the time travel
const previous = document.getElementById('previous');
const next = document.getElementById('next');
previous.addEventListener('click', e => {
e.preventDefault();
e.stopPropagation();
let index = activeItem - 1;
index = index <= 0 ? 0 : index;
activeItem = index;
const desiredState = timeline[index];
store.setState(desiredState);
});
next.addEventListener('click', e => {
e.preventDefault();
e.stopPropagation();
let index = activeItem + 1;
index = index >= timeline.length - 1 ? timeline.length - 1 : index;
activeItem = index;
const desiredState = timeline[index];
store.setState(desiredState);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment