admin管理员组文章数量:1181399
This error is in the console and it prevents the app from working, I cant find the bug at all if anyone could help? Its a MERN application
The code in question
export const getPosts = () => async (dispatch) => {
try {
const { data } = await api.fetchPosts();
dispatch({ type: 'FETCH_ALL', payload: data });
} catch (error) {
console.log(error.message);
}
};
VSC is telling me await doesn't effect this kind of expression, which it should as fetchPosts is a request? The code for this is below
export const fetchPosts = () => {
axios.get(url)
}
This error is in the console and it prevents the app from working, I cant find the bug at all if anyone could help? Its a MERN application
The code in question
export const getPosts = () => async (dispatch) => {
try {
const { data } = await api.fetchPosts();
dispatch({ type: 'FETCH_ALL', payload: data });
} catch (error) {
console.log(error.message);
}
};
VSC is telling me await doesn't effect this kind of expression, which it should as fetchPosts is a request? The code for this is below
export const fetchPosts = () => {
axios.get(url)
}
Share
Improve this question
edited Feb 23, 2021 at 20:15
Emile Bergeron
17.4k5 gold badges84 silver badges131 bronze badges
asked Feb 23, 2021 at 19:54
Dan WilstropDan Wilstrop
4351 gold badge5 silver badges15 bronze badges
2
- 2 Does this answer your question? When should I use a return statement in ES6 arrow functions – Emile Bergeron Commented Feb 23, 2021 at 20:15
- Thank you for the help – Dan Wilstrop Commented Feb 23, 2021 at 20:42
2 Answers
Reset to default 22The problem is that, although axios.get
may return a promise, the fetchPosts
function you've wrapped it in doesn't return the promise that axios.get
returns:
const fetchPosts = () => {
axios.get(url);
};
const myFetch = await fetchPosts();
console.log(myFetch); // will log `undefined`
If you rewrite fetchPosts
as so:
export const fetchPosts = () => axios.get(url);
...with the implicit return from your arrow function, I think it should work. Alternatively, you could just explicitly return the result of axios.get
:
const fetchPosts = () => {
return axios.get(url);
};
...but your linter may complain about that.
let's try to return a Promise from the function, that use axios:
export const fetchPosts = async () => return await axios.get(url);
And then you can use destructuring at then
-block of handling Promise
export const getPosts = async dispatch => {
await fetchPosts()
.then({data}) => dispatch({ type: 'FETCH_ALL', payload: data)
.catch(error => {console.log(error.message)});
}
本文标签:
版权声明:本文标题:javascript - Cannot destructure property 'data' of '(intermediate value)' as it is undefined - S 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738253665a2071493.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论