Cannot destructure property 'data' of '(intermediate value)' as it is undefined

Dan*_*rop 3 javascript reactjs

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

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

Ale*_*ied 5

The 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 = fetchPosts();

console.log(myFetch); // will log `undefined`
Run Code Online (Sandbox Code Playgroud)

If you rewrite fetchPosts as so:

export const fetchPosts = () => axios.get(url);
Run Code Online (Sandbox Code Playgroud)

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

...but your linter may complain about that.

  • @DanWilstrop 是的,那也行。你基本上需要返回一个承诺。您在该函数中执行其他操作并不重要。 (2认同)
  • 抱歉,我之前错过了回复——感谢 @GabrielePetrioli 的插话。很高兴这有帮助,祝你好运,编码愉快! (2认同)