这是indexloc提供的服务,不要输入任何密码
Skip to content

recoil-persist not working as expected with useSetRecoilState in the useEffect hook #64

@sarobolket

Description

@sarobolket

I want to update an atom with the query string in the URL. With useSetRecoilState I can set the atom but recoil-persist doesn't save in localStorage. I can see that the onSet callback in the effects of the atom is not triggered.

See this example:

import { atom } from 'recoil';
import { recoilPersist } from 'recoil-persist';

const { persistAtom } = recoilPersist();

export const atomState = atom({
  key: 'example',
  default: null,
  effects: [persistAtom],
});

import React from 'react';
import { Navigate } from 'react-router-dom';
import { useRecoilValue } from 'recoil';
import { atomState } from 'state';
import { useSaveQueryString } from 'hooks/useSaveQueryString';

function MobileRoute() {
  useSaveQueryString ();

  const state = useRecoilValue(atomState );

  if (state ) {
    return <Navigate to="/something" />;
  }

  return <div>Loading...</div>;
}

export default MobileRoute;
function useSaveQueryString () {
  const [search] = useSearchParams();
  const setAtom = useSetRecoilState(atomState);

useEffect(() => {
const searchAsObject = Object.fromEntries(new URLSearchParams(search));

  if (searchAsObject.id) {
    setAtom (searchAsObject.id);
  }
}, [search, setAuth])
}

How can I solve it? Some example with recoil-sync??

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions