如何根据第一个响应进行第二个 API 调用? [英] How to make a second API call based on the first response?

查看:28
本文介绍了如何根据第一个响应进行第二个 API 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用 2 个 API 来在我的组件上显示数据,但第二个 API 需要来自第一个 API 响应的标头.我正在使用 React Hooks.我从第一个响应更新状态,以便稍后我可以在第二个调用中使用它,但它未定义.我做错了什么?

I need to call 2 APIs for displaying data on my component but the second api needs headers from the response of first API. I am using React Hooks. I update the state from the first response so i can use it later for the second call, but it goes undefined. What am i doing wrong?

P.s 执行此调用的更好方法(可能使用 async/await)将非常有用

P.s a better way of doing this calls (maybe using async/await) would be much appriciated

 const [casesHeaderFields, setCasesHeaderFields] = useState([]);
 const [casesFields, setCasesFields] = useState([]);

  useEffect(() => {
    const fetchData = () => {
      const result1 = axios
        .get(`firstUrl`)
        .then(response => {
         //I need this as headers for my second API
          setCasesHeaderFields(
            response.data.result.fields
          );
        });

      const result2 = axios
        .get(`url${casesHeaderFields} //here i want to pass params from 
         //first response)
        .then(response => {
          setCasesFields(response.data.result.record_set);
        });
    };
    fetchData();
  }, []);

推荐答案

在 .then 中进行第二次调用,链接到第一个承诺链的末尾......简单来说,链接你的承诺

make the second call inside a .then chained to the end of the first promise chain ... in simple terms, chain your promises

类似的东西

useEffect(() => axios.get(`firstUrl`)
    .then(response => {
        setCasesHeaderFields(response.data.result.fields);
        return response.data.result.fields;
    })
    .then(casesHeaderFields => axios.get(`url${casesHeaderFields}`))
    .then(response => {
        setCasesFields(response.data.result.record_set);
    }), []);

这篇关于如何根据第一个响应进行第二个 API 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆