[Tips] Updating atom object property
See original GitHub issueAtoms can hold any primitive values, including objects. Here’s an example to updating a property of an object.
const funkyPigAtom = atom({ funkyPig: { glasses: 'stylish', bling: 'golden' }})
const Component = () => {
const [funkyPig, setFunkyPig] = useAtom(funkyPigAtom)
const updateBling = (bling) => {
setFunkcyPig((prev) => ({ ...prev, funkyPig: { ...prev.funkyPig, bling } }))
}
// ...
}
We could also create an update action atom.
const funkyPigAtom = atom({ funkyPig: { glasses: 'stylish', bling: 'golden' }})
const updateBling = atom(
null,
(get, set, bling) => {
const prev = get(funkyPigAtom)
set(funkyPigAtom, { ...prev, funkyPig: { ...prev.funkyPig, bling } })
}
)
Issue Analytics
- State:
- Created 3 years ago
- Reactions:5
- Comments:8 (4 by maintainers)
Top Results From Across the Web
How to update Recoil JS Atom Object - Stack Overflow
You need to combine the previous state and updated state like this setWallet((prevState) => ({ ...prevState, connected: true, }));.
Read more >Updating JavaScript Object Property - React Tips
The solution is to copy object : const newObject = {...object}; and then update value of a copy: newObject[property] = "Updated value"; and...
Read more >atom(options) - Recoil
The atom() function returns a writeable RecoilState object. ... If a selector is used as the default the atom will dynamically update as...
Read more >How do you rerender a React component when an object's ...
I have an object in my React application which is getting updated from another system. I'd like to display the properties of this...
Read more >How to define custom atom names
In the diagram, right-click the descriptor for the object you want to customize atom names for and select Properties to open the Object...
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
Ooooh, you guys are the best! I am learning about Observer Patterns in JS and wanted to write a state management lib using OP for giggles, so I found this, which led me here (and to Recoil) and now I’m just writing a handlers layer on top of Jotai to learn how stuff works. @dai-shi thanks a lot for doing all this 😉
@dai-shi You’re way ahead of me, thanks! 😃 Maybe I should spend more time looking through all these issue!