Categories
discuss

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

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)
}

Answer

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`

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.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..