Best way to create a new atom based on another atom's data #1046
-
Hey, I'm looking for advice on if I'm approaching this correctly or if there is a more straight forward approach to this. I'm looking for a way to add a new atom to an array of atoms that uses some data from the last atom in the array however the data also has an array of atoms that need to be duplicated into a new atom (so that they are updated independently). I've got it working by using the useAtomCallback to read data then create a new atom, I've added some simplified pseudo code of my approach so far. const outerAtom = atom({
...someData,
foos: [
atom({
name: 'a',
bars: [
atom({name: 'a', count: 2}),
atom({name: 'b', count: 7})
]
})
]
})
const MyComponent = () => {
const [data, setData] = useAtom(outerAtom);
const readLastFoo = useAtomCallback(
useCallback((get) => {
const lastFoo = get(outerAtom.foo[outerAtom.foo.length - 1])
return {
...lastFoo,
foos: last.foo.map(fooAtom => {
const fooData = get(fooAtom)
return fooData
})
};
}, [])
)
const addNewFoo = async () => {
const lastFoo = await readLastFoo();
const newFoo = atom({
...lastFoo,
name: 'b',
foos: lastFoo.foos.map(foo => atom({...foo, count: 0}))
})
setData(prev => ({...prev, foos: [...prev.foos, newFoo]}))
}
return (
<div>
<h1>Some title</h1>
{data.foos.map(fooAtom => <Child fooAtom={fooAtom} key={`{fooAtom}`} />}
<button onClick={addNewFoo}>add new foo</button>
</div>
)
} Any advice on how to achieve this in a cleaner way would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I would simply define an action atom. const outerAtom = atom(...)
const addNewFooAtom = atom(null, (get, set) => {
...
})
const MyComponent = () => {
const [data, setData] = useAtom(outerAtom);
const [, addNewFoo] = useAtom(addNewFooAtom);
...
} |
Beta Was this translation helpful? Give feedback.
I would simply define an action atom.