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

onSet is not triggered when using useRecoilState #2294

Open
hjk329 opened this issue Oct 30, 2023 · 2 comments
Open

onSet is not triggered when using useRecoilState #2294

hjk329 opened this issue Oct 30, 2023 · 2 comments

Comments

@hjk329
Copy link

hjk329 commented Oct 30, 2023

Hi, team.

I'm using recoil-persist to save atom in local storage.

I found out that onSet is not triggered when using useRecoilState.
However, it is executed when using useSetRecoilState.

I'm using recoil 0.7.7, the latest version, and Next.js 12.3.2.

I looked through your document, describing onSet as Subscribe to changes in the atom value..

Below is the source code. Atom is updated, but it is not stored in the local storage.

import {atom} from "recoil";
import {recoilPersist} from "../utils/recoil-persist";

const {persistAtom} = recoilPersist()

const authAtom = atom({
    default: 'hj',
    key: 'authAtom',
    effects_UNSTABLE: [persistAtom],
})

const GNB = () => {
    const [auth, setAuth] = useRecoilState(authAtom);

    useEffect(() => {
        setAuth('eden')
    }, [])

    return (
        <div>
            <p>{auth}</p>
        </div>
    )
}

In my understanding, onSet should be called when the atom has new value (default: 'hj' -> new value: 'eden').

Using useSetRecoilState, however, it is saved in the storage.

const GNB = () => {
    const setAuth = useSetRecoilState(authAtom);

    return (
        <div>
            <p>{auth}</p>
        </div>
    )
}

Would you please let me know why onSet is not triggered when using useRecoilState?
Or, is there anything that I misunderstood using useRecoilState and onSet?

@Gamez0
Copy link

Gamez0 commented Nov 8, 2023

can you add the version of recoil-persist you use?

@kis0421
Copy link

kis0421 commented Dec 13, 2023

@hjk329
There are no issues with recoil-persist or onSet.

This is a problem that occurs very strictly in the mode.
This is related to an issue where two connections are required to identify a bug in Strict mode.
So in a production environment there will be no problem.

  1. Try removing the React.StrictMode component
  2. Try running it after building, not in dev mode.
  3. Run the setter within the cleanup function of useEffect.

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

3 participants