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

why dose useLocalStorage use custom event? #311

Open
jakkku opened this issue Jun 20, 2024 · 0 comments
Open

why dose useLocalStorage use custom event? #311

jakkku opened this issue Jun 20, 2024 · 0 comments

Comments

@jakkku
Copy link

jakkku commented Jun 20, 2024

Hi, first of all, thank you for providing a nice library.
I love this and am learning a lot

I have some questions.
In your code, The useLocalStorage hook uses a custom event internally.
However, custom events could be triggered by not only internal function, but also other external functions anywhere.

I thought using local scope variable is more safe.
but if you have some reason using CustomEvent, could i ask??

// This is an example of a third-party store
// that you might need to integrate with React.

// If your app is fully built with React,
// we recommend using React state instead.

let nextId = 0;
let todos = [{ id: nextId++, text: 'Todo #1' }];
let listeners = [];

export const todosStore = {
  addTodo() {
    todos = [...todos, { id: nextId++, text: 'Todo #' + nextId }]
    emitChange();
  },
  subscribe(listener) {
    listeners = [...listeners, listener];
    return () => {
      listeners = listeners.filter(l => l !== listener);
    };
  },
  getSnapshot() {
    return todos;
  }
};

function emitChange() {
  for (let listener of listeners) {
    listener();
  }
}
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

1 participant