Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@dzcpy I think if we use two atoms, the history can be implemented. No need for onMount in this case. #645

Closed
IanDuncanson opened this issue Aug 8, 2021 · 2 comments

Comments

@IanDuncanson
Copy link

@dzcpy I think if we use two atoms, the history can be implemented. No need for onMount in this case.
The good way to think at first is how you would do it with useState. Then, it's straightforward to migrate to atom and useAtom. I can help on it.
Would you open a new discussion / issue?

Originally posted by @dai-shi in #211 (comment)

@IanDuncanson
Copy link
Author

@dai-shi - I am interested in how you might achieve undo redo history with atoms?

@dai-shi
Copy link
Member

dai-shi commented Aug 8, 2021

Something like this:

const initialValue = 'hello'

const historyAtom = atom({
  history: [initialValue],
  index: 0,
})

const valueAtom = atom(
  (get) => {
    const { history, index } = get(historyAtom)
    return history[index]
  },
  (get, set, action) => {
    const { history, index } = get(historyAtom)
    if (action.type === 'update') {
      set(historyAtom, {
        history: [...history.slice(0, index + 1), action.value],
        index: index + 1,
      })
    } else if (action.type === 'undo' && index > 0) {
      set(historyAtom, { history, index: index - 1 })
    } else if (action.type === 'redo' && index < history.length - 1) {
      set(historyAtom, { history, index: index + 1 })
    }
  }
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants