How to set a new state using async API call
See original GitHub issueI’m trying to implement basic features to a project using Recoil, just to test the library. I’m really liking what I’m seeing. However, I have a doubt regarding to updating a state based on an async API call, i.e., I created the following selectors
to fetch from API:
export const teamsState = selector({
key: "teams",
get: async ({ get }) => {
try {
const response = await api.get("/teams");
return response.data.teams;
} catch (e) {
throw e;
}
},
});
export const teamById = (id) =>
selector({
key: "teamById",
get: ({ get }) => {
const teams = get(teamsState);
return teams.filter((team) => team._id === id)[0];
},
});
The teamsState
fetch a list of teams
from the API, and the teamById
returns the selected team
from the list of teams.
My doubt comes now. If I need to add a new team, how should I proceed?
I have a route to add a team in my backend, and the response is the object team I added, not a list of teams. So, how should I update the teamsState
to reflect this added object? Should I get all teams again, making an API call to get the list of teams (this doesn’t seem the right choice, but would work)?
Great work on bringing this new library to the React environment!
Issue Analytics
- State:
- Created 3 years ago
- Comments:15 (4 by maintainers)
Top GitHub Comments
تزكروني باني احبكم جدا
هااي