Value from localStorate is null not return default value
hiimnhan opened this issue · comments
When I get item with key from recoil-persist, value seems to be null instead of default value.
Codesandbox: https://codesandbox.io/s/eloquent-hypatia-k2eb4?file=/src/App.js
I am not sure about effect localStorageEffect
but If I add a recoil-persist effect to atom then I can see the non null value in console:
const { persistAtom } = recoilPersist({ key: "auth" });
const counterState = atom({
key: "count",
default: 1,
effects_UNSTABLE: [persistAtom]
});
export default function App() {
const [count, setCount] = useRecoilState(counterState);
console.log(count);
console.log("persist", window.localStorage.getItem("auth"));
https://codesandbox.io/s/lucid-forest-teu5h?file=/src/App.js
Your solution works pretty good with primitive type. But when i change default to an object {id: 1, name: ''} an error appears
Objects are not valid as a React child (found: object with keys {id}). If you meant to render a collection of children, use an array instead.
Codesandbox: https://codesandbox.io/s/lucid-forest-teu5h?file=/src/App.js
@hiimnhan this error is from React, because React could not render the object, we have to get values by keys in JSX:
Codesandbox: https://codesandbox.io/s/lucid-forest-teu5h?file=/src/App.js
const { persistAtom } = recoilPersist({ key: "auth" });
const counterState = atom({
key: "count",
default: { id: 1, name: "" },
effects_UNSTABLE: [persistAtom]
});
export default function App() {
const [person, setPerson] = useRecoilState(counterState);
console.log(person);
console.log("persist", window.localStorage.getItem("auth"));
return (
<div>
<h3>Id: {person.id}</h3>
<h3>Name: {person.name || "[Empty Name]"}</h3>
<button onClick={() => setPerson({ ...person, id: 12 })}>
Set id to 12
</button>
<button onClick={() => setPerson({ ...person, name: "John" })}>
Set name to 'John'
</button>
</div>
);
}
Looks like this issue was not recoil-persist related. I am closing this issue