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

new util useAtomCallback #140

Merged
merged 4 commits into from
Oct 17, 2020
Merged

new util useAtomCallback #140

merged 4 commits into from
Oct 17, 2020

Conversation

dai-shi
Copy link
Member

@dai-shi dai-shi commented Oct 17, 2020

close #60

  • impl
  • examples
  • docs

Examples

import * as React from "react";
import { useEffect, useState, useCallback } from "react";
import { Provider, atom, useAtom } from "jotai";
import { useAtomCallback } from "jotai/utils";
import "./styles.css";

const countAtom = atom(0);

const Counter = () => {
  const [count, setCount] = useAtom(countAtom);
  return (
    <>
      {count} <button onClick={() => setCount((c) => c + 1)}>+1</button>
    </>
  );
};

const Monitor = () => {
  const [count, setCount] = useState(0);
  const readCount = useAtomCallback(
    useCallback((get) => {
      const currCount = get(countAtom);
      setCount(currCount);
      return currCount;
    }, [])
  );
  useEffect(() => {
    const timer = setInterval(async () => {
      console.log(await readCount());
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, [readCount]);
  return <div>current count: {count}</div>;
};

const App = () => (
  <Provider>
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Counter />
      <Monitor />
    </div>
  </Provider>
);

export default App;

https://codesandbox.io/s/react-typescript-forked-6ur43?file=/src/App.tsx

@codesandbox-ci
Copy link

codesandbox-ci bot commented Oct 17, 2020

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 82bed93:

Sandbox Source
React Configuration
React Typescript Configuration
React Typescript (forked) PR

@dai-shi
Copy link
Member Author

dai-shi commented Oct 17, 2020

I look forward to someone working on better examples, docs and tests.

@dai-shi dai-shi merged commit e8637b4 into master Oct 17, 2020
@dai-shi dai-shi deleted the feat/use-atom-callback-util branch October 17, 2020 11:23
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

Successfully merging this pull request may close these issues.

Is it possible to read an atom's current state without using useAtom?
1 participant