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);
})
}, []);
CodePudding user response:
You're close but there's a few problems:
- You don't return anything from your Promise handlers, so some of your variables are undefined.
- (related to #1) There's basically never a reason to have nested
.then
s - As collinD points out in the comments you aren't
.catch
ing any errors on the second call. - Instead of
console.log
for errors you probably wantconsole.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();
}, []);