Atoms initialised with defaultValue from an fetch-api selector behave differently after 'set' operation
See original GitHub issueI am currently working on a TODO app with API interaction. I have two atoms, one for tracking Query-Refresh and the other is List-Atom contains the TODO List from the server.
The APIs are GET List, ADD Item, Delete Item.
The Atoms look like the following:
export const triggerRefreshTodosAtom = atom({
key: 'triggerRefreshTodosAtom',
default: 0,
});
export const getTodosSelector = selector({
key: 'getTodosSelector',
get: async ({ get }) => {
// Register 'triggerRefreshTodosAtom' as a dependency.
get(triggerRefreshTodosAtom);
try {
const response = await getTodos();
return response || [];
} catch (error) {
console.error(`getGreetingsSelector -> getGreetings() ERROR: \n${error}`);
return [];
}
},
});
export const todosAtom = atom({
key: 'todosAtom',
default: getTodosSelector,
});
I have two components AddTodo and TodoList containing delete-button for each-todos. Both of them are in separate routes. Every time I add a Todo, on the success of the API call, I increment triggerRefreshTodosAtom in order to trigger the list update, which happens when I switch to the TodoList component route, as it is the dependency for the getTodosSelector.
Problem: The real problem is when I try to do a set on the todosAtom to track the deleted list-items locally without triggering a re-fetch of the query the AddTodo query-fresh logic no longer works. Meaning it no longer tracks the triggerRefreshTodosAtom updates to do a query-refresh.
If this is not a known problem, I can also try and create a codesandbox for the same.
Issue Analytics
- State:
- Created 2 years ago
- Comments:10 (4 by maintainers)
Top GitHub Comments
Ah, so it sounds like this is expected behavior, then? Yes, if an atom has a default value which is a selector then it will use that selector value (which may be dynamic) until the atom is set and then it will use that set value. When the atom value is set it sticks with that set value and won’t change dynamically as it is using the set value instead of the fallback selector. If the atom is reset, then it reverts to the dynamic selector again. If you want something that is always dynamic and updates based on dependencies then perhaps you should consider using a selector instead of an atom.
Yes I have seen this one. But isnt it same as setting the atoms directly ?? If I use selector set to modify atoms it would also overwrite the default selector value ?? No ??. May be I need to rethink the architecture a bit!
On Wed 13. Oct 2021 at 23:53, Douglas Armstrong @.***> wrote: