Anjanesh

Anjanesh

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)
    {
        axios
        .get('/api/current_user')
        .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') });
 
Share this