14

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)
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Dan Wilstrop
  • 355
  • 1
  • 4
  • 12

1 Answers1

16

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.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • 1
    amazing, thank you, this has been driving me crazy for two hours! Not that i would but would setting const info = axios.get(url) and then return info have the same effect? Much better as one line just trying to understand the JS behind it more? – Dan Wilstrop Feb 23 '21 at 20:09
  • 2
    @DanWilstrop yes, that would also work. You basically need to return a promise. Does not matter what else you do in the function. – Gabriele Petrioli Feb 23 '21 at 20:18