I can get list with get axios.get method. then ı can use setState and it works flawlessly. but the return is not true , its return undefined console.log(result) => undefined . How can ı check if setState work fine return true or return false ?
JavaScript
x
19
19
1
getList = async () => {
2
await axios.get("http://localhost:5000/list").then((response) => {
3
this.setState(
4
{
5
copy: response.data.list,
6
},
7
() => {
8
return true;
9
},
10
);
11
});
12
};
13
14
componentDidMount = () => {
15
this.getList().then((result) => {
16
console.log(result);
17
});
18
};
19
Advertisement
Answer
Your return true
statement is in setState
‘s post-set callback. It won’t be propagated to the promise that’s returned from getList
; indeed, you return nothing from that function (you don’t even return the Axios promise; if you did return that, you would get the response logged in your console.log
, but it would be logged before the setState
callback finished), so you get undefined
in the console.log
.
If you need getList
to return a promise that resolves to true
once the state has been set, you’ll need
JavaScript
1
19
19
1
getList = () => {
2
return new Promise((resolve) =>
3
axios.get("http://localhost:5000/list").then((response) =>
4
this.setState(
5
{
6
copy: response.data.list,
7
},
8
() => resolve(true),
9
),
10
),
11
);
12
};
13
14
componentDidMount = () => {
15
this.getList().then((result) => {
16
console.log(result);
17
});
18
};
19