How to make a second API call based on the first response?

Bes*_*rku 1 javascript reactjs axios

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 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();
  }, []);
Run Code Online (Sandbox Code Playgroud)

PEP*_*EGA 7

You can chain the results as they are regular promises: Ref

axios.get(...)
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('Response', response);
  });
Run Code Online (Sandbox Code Playgroud)


Jar*_*a X 5

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

就像是

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);
    }), []);
Run Code Online (Sandbox Code Playgroud)