One liner ES6 refactor

How this function can be refactored to just one line !

This is a function returning a function that calls redux's dispatch() function manually.

export const fetchUser = () =>
    return function(dispatch)
        .then(res => dispatch({ type: FETCH_USER, payload: res }));

This can be re-written to using async + await.

export const fetchUser = () => async dispatch =>
    const res = await axios.get('/api/current_user');
    dispatch({ type: FETCH_USER, payload: res });

And the above can be rewritten using a single line since the variable res is used only once.

export const fetchUser = () => async dispatch => dispatch({ type: FETCH_USER, payload: await axios.get('/api/current_user') });

Comments (2)

Darlan Todero ten Caten's photo

Please don't. The last code can be small but is very difficult to be readen fast by anyone. Come back to that code in 3 months from now and you will see that you will need a couple of seconds to understand it.

The code must be easy to follow. The first refactor with async/await is perfect, stick with it.

Anjanesh Lekshminarayanan's photo

Yes, I totally agree that #3 is difficult to read even for experienced JavaScript coders. I was just trying to give an example of how sometimes it's possible to condense code to just one line JavaScript. I am going through this tutorial on MERN full-stack by Stephen Grider and came across this.