Writeable Atom with derived default value
See original GitHub issueI just recently went through a refactoring from recoil. Everything was pretty straightforward but one use case I couldn’t build in jotai.
I have a list of countries I can fetch from the backend:
const availableCountriesApi = atom<Array<Country>>(async () => fetchEntities("/core/countries"))
I built a defaultCountry atom based on this fetch
const defaultCountry = atom<Country>(
(get) => get(availableCountries).find(country => country.id === "US") || {id: "US", name: "United States"},
)
And now I have a selectedCountry
atom which I want to initialize with the default country. But everything I tried resulted either in a type error or a readable only atom:
const selectedCountryState = atom<Country>((get) => get(defaultCountry))
const [selectedCountry, setSelectedCountry] = useAtom(selectedCountryState)
setSelectedCountry({id: "DE", name: "Germany"}) // This expression is not callable, Type 'never' has no call signatures.
I think the async fetch is not super relevant, because when I change my defaultCoutry atom to this, I’ll run in the same problem:
const defaultCountry = atom<Country>({id: "US", name: "United States"})
So is there a way to build a writeable atom that I can initialize with a derived atom value?
Issue Analytics
- State:
- Created 3 years ago
- Comments:13 (7 by maintainers)
Top Results From Across the Web
atomWithDefault - Jotai
This is a function to create a resettable primitive atom. Its default value can be specified with a read function instead of a...
Read more >atom(options) - Recoil
An atom represents state in Recoil. The atom() function returns a writeable RecoilState object. ... default - The initial value of the atom....
Read more >Storing function as jotai atom? - reactjs - Stack Overflow
The idea is to create Jotai state and derived state. The latter will contain the logic of the function you want to share...
Read more >/docs/guides/composing-atoms.mdx | jotai@v1.5.2 | Deno
Obviously read-only atoms are not writable, but we can combine two atomsto override the read-only atom value. ```js ...
Read more >Jotai: The Ultimate React State Management - 100ms
Jotai, the atom-based state management for React. ... we have to fallback to the default value of light if it's running in the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Oh sorry, didn’t see. Now it works. Thank you so much!
Actually, it might be possible to implement it with just one atom, using some undocumented properties. We already did
atomWithReducer
similarly, so let me work on it.