如何解决按名称反应redux Fetch ID,并使用该ID进行另一个API调用
我正在尝试使用API端点通过用户名(段)获取ID。使用该用户ID,我可以进行下一个调用以获取用户数据。我想为其创建一个自定义钩子,因为我认为它会在以后的相当长的时间内重复出现。我想避免每次都要将ID存储在redux状态。我只想获取结果(id),并将其用于下一次通话。该调用的结果将存储在redux状态。
如何使用干净的方法来链接这些API调用。
- 动作将slug作为参数接收,以通过slug获取ID。
- 使用API调用的结果并将其传递给下一个操作
- 操作将ID接收为参数,并使用ID来获取信息
- 将结果存储为redux状态
组件:
const UserInfoContainer = () => {
const { slug } = useParams();
const dispatch = useDispatch();
// So here I get the slug from the URL.
useEffect(() => {
dispatch(fetchUserIdBySlug(slug));
},[dispatch,slug]);
};
获取ID的操作:
export const fetchUserIdBySlug = (slug) => {
return (dispatch) => {
dispatch(fetchUserIdBySlugRequested(slug));
return (
fetchApi(`api/path/fetch/by/${slug}`,{
method: 'GET',credentials: 'include',headers: {
'Content-Type': 'application/json',},})
// the ID is in the result
.then((res) => {
dispatch(fetchUserIdBySlugSucceeded(res));
})
.catch((err) => {
dispatch(fetchUserIdBySlugFailed(err));
})
);
};
};
通过ID提取信息的操作:
export const fetchUserInfoById = (
id
) => {
return (dispatch) => {
dispatch(
fetchUserInfoByIdRequested(id)
);
return fetchApi(
`api/path/user/${id}/info`,{
method: 'GET',headers: {
'Content-Type': 'application/json',}
)
.then((res) => {
dispatch(fetchUserInfoByIdSucceeded(res));
})
.catch((error) => {
dispatch(fetchUserInfoByIdoFailed(error));
});
};
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。