在收到第一个api的响应后,向另一个api发出请求



我想从第一个api的res.data信息中获取res.data.login信息,并将其发送到第二个api

然后我想从第二个api 中得到结果

const [user, setUser] = useState(null);
const [projects,setProjects]=useState(null)
useEffect(() => {
axios.get("http://localhost:5000/user", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
setUser(res.data);
})
.catch((error) => {
console.log("error " + error);
});
const username = user.login
axios.get(`http://localhost:5000/projects`,{
headers:{
username:username,
}
}).then((response)=>{
setProjects(response.data)
})
}, []);

我找过类似的问题,但找不到解决办法。

您需要获取用户的信息,以获得您可能想要调用第一个API同步获取的项目。

但是useEffect钩子中的await不能同步调用函数。

有一个解决方案。请定义async函数,并在其中运行2个API获取函数。

这是一个钩子代码。

useEffect(() => {
const asyncFunc = async () => {
const res = await axios.get("http://localhost:5000/user", {
headers: {
Authorization: `Bearer ${token}`,
},
});
setUser(res.data);
axios.get(`http://localhost:5000/projects`,{
headers:{
username:res.data.login,
}
}).then((response)=>{
setProjects(response.data)
});
}
asyncFunc();
}, []);

两个选项。。。

选项1

将第二个Axios调用从第一个移动到.then()

useEffect(() => {
axios
.get("http://localhost:5000/user", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then(({ data: userData }) => {
setUser(userData);
return axios
.get("http://localhost:5000/projects", {
headers: { username: userData.login }, // use response data here
})
.then(({ data: projectsData }) => {
setProjects(projectsData);
});
})
.catch(console.error);
}, []);

选项2

user作为依赖在效果挂钩中激发第二个请求

useEffect(() => {
axios
.get("http://localhost:5000/user", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then(({ data }) => {
setUser(data);
})
.catch(console.error);
}, []);
useEffect(() => {
if (user) { // only run once user is not null
axios
.get("http://localhost:5000/projects", {
headers: { username: user.login }, // use state data here
})
.then(({ data }) => {
setProjects(data);
})
.catch(console.error);
}
}, [user]);

相关内容

最新更新