Is this a good way to use the response from the first call to use it on the second?

I am new to Reactjs and i wanted to link 2 requests together. It works but i wanted to know if there was a better way to do this.

Here’s my code

const [data, setData] = useState([]);
const [data2, setData2] = useState([]);
useEffect(() => {
    axios.get(api, config)
        .then(res => {
            setData(res.data);
        })
        .then(res => {
            let id = data.compte.id;
            axios.get(`http://localhost:8000/api/compte/${id}`, config).then(res => {
                setData2(res.data);
            })
        })
        .catch(err => {
            console.log(err);
        })
}, []);

>Solution :

You’re close but there’s a few problems:

  1. You don’t return anything from your Promise handlers, so some of your variables are undefined.
  2. (related to #1) There’s basically never a reason to have nested .thens
  3. As collinD points out in the comments you aren’t .catching any errors on the second call.
  4. Instead of console.log for errors you probably want console.error.
const [data, setData] = useState([]);
const [data2, setData2] = useState([]);
useEffect(() => {
    axios.get(api, config)
        .then(res => {
            setData(res.data);
            let id = res.data.compte.id;
            return axios.get(`http://localhost:8000/api/compte/${id}`, config)
        })
        .then(setData2)
        .catch(err => {
            console.error(err);
        })
}, []);

This whole thing would arguably look cleaner with async/await:

const [data, setData] = useState([]);
const [data2, setData2] = useState([]);
useEffect(() => {
  const fn = async () => {
    try {
      const res = await axios.get(api, config);
      setData1(res);
      const id = res.data.compte.id;
      const res2 = await axios.get(`http://localhost:8000/api/compte/${id}`, config);
      setData2(res2);
    } catch (err) {
      console.error(err);
    }
  }

  fn();
}, []);

Leave a Reply