How to update selector's 'temporary' value and do a request to api at the same time
See original GitHub issueHey guys!
I’m fascinated by this library and wanted to try it out. I came across a use case where I have to display to the user what he’s changed in the UI while making a request to the server to save that data.
Here is my selector to retrieve the data:
export const eventsListQuery = selector({
key: "eventsList",
get: async ({ get }): EventType[] => {
const currentUser = get(userState);
return await fetchEvents(currentUser);
},
});
Then I render events
, each event item gets only its id from props and selects the event data using this selector:
export const eventItemQuery = selectorFamily({
key: "eventItem",
get: (eventId: string) => ({ get }): EventType => {
return get(eventsListQuery).find((event: EventType) => event.id === eventId);
},
});
The user can change almost anything in the data, so I wanted to have this selector updating the state in a way that I could render some updates everywhere it’s being used and send a request to the server to get it updated on the backend side at the same time.
I tried to use set
method of a selectorFamily but it throws an error indicating that eventsList
could not be updated because it’s read-only which is I guess make sense.
export const eventItemQuery = selectorFamily({
key: "eventItem",
get: (eventId: string) => ({ get }): EventType => {
return get(eventsListQuery).find((event: EventType) => event.id === eventId);
},
set: (currentItem: EventType) => ({ set, get }, updatedValue) => {
const events = get(eventsListQuery).map((event: EventType): EventType => {
if (event.id === currentItem.id) return { ...event, ...updatedValue };
return event;
});
set(eventsListQuery, events);
},
});
My question is, how can I achieve that user experience using Recoil?
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
Please note that the effect function itself should not be
async
. Though, you can set the initialsetSelf()
to aPromise
.We are exploring some ability to read other state from the handlers, perhaps though a
getSnapshot()
approach.Consolidate discussion of getting other state from effects in #707