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

[Question] How to use addEventListener in unstated-next #93

Open
mdyu1000 opened this issue Jan 9, 2021 · 0 comments
Open

[Question] How to use addEventListener in unstated-next #93

mdyu1000 opened this issue Jan 9, 2021 · 0 comments

Comments

@mdyu1000
Copy link

mdyu1000 commented Jan 9, 2021

I want to use event listener in createContainer,
but I found click event and keydown event listener would log twice, and it's different result.
I don't know what cause it.

Could someone help explain

Here's my code: https://codesandbox.io/s/unstated-next-forked-p9fe4?file=/src/unstated.js:0-717

index.js

import React from "react";
import ReactDOM from "react-dom";
import CounterContainer from "./unstated";
import Counter from "./component";

import "./styles.css";

function App() {
  return (
    <div className="App">
      <CounterContainer.Provider>
        <Counter />
      </CounterContainer.Provider>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Component

import React from "react";
import CounterContainer from "./unstated";

import "./styles.css";

function Counter() {
  const counter = CounterContainer.useContainer();

  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
    </div>
  );
}

export default Counter;

unstated-next

import { createContainer } from "unstated-next";
import { useState, useEffect, useCallback } from "react";

function useCounter() {
  const [count, setCount] = useState(0);

  const decrement = () => setCount(count - 1);
  const increment = useCallback(() => setCount(count + 1), [count]);

  const handleKeyDown = useCallback(
    (event) => {
      console.log("current count", count);
      setCount(count + 1);
    },
    [count]
  );

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [handleKeyDown]);

  return { count, decrement, increment };
}

export default createContainer(useCounter);
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