Phoenix
Phoenix

Reputation: 445

What's better approach for Redux Action Creator: .then or async/await syntax?

For example comparing the two codes below, the first one using async/await and the other calling axios with .then.

What code is recommended?

const BASE_URL = "https://jsonplaceholder.typicode.com"

// async await syntax
export const fetchPosts = () => async dispatch => {
  const response = await axios.get(BASE_URL + "/posts")
  dispatch({ type: "FETCH_POSTS", payload: response })
}

// using .then instead
export const fetchPosts2 = () => dispatch => {
  axios.get(BASE_URL + "/posts").then(response =>
    dispatch({
      type: "FETCH_POSTS",
      payload: response
    })
  )
}

Upvotes: 0

Views: 76

Answers (1)

Blue
Blue

Reputation: 22911

They're both essentially identical. The only thing it comes down to is pure preference. I personally prefer the async/await syntax because it can save you some potential headaches when doing multiple calls, avoiding some particually nasty nested calls:

// async await syntax
export const fetchPosts = () => async dispatch => {
  const posts = await axios.get(BASE_URL + "/posts")
  const users = await axios.get(BASE_URL + "/users", {
    params: posts.map(p => p.author_id)
  })
  dispatch({ type: "FETCH_POSTS", payload: {
      posts, users
  }})
}

vs:

// async await syntax
export const fetchPosts = () => dispatch => {
  axios.get(BASE_URL + "/posts").then(posts =>
    axios.get(BASE_URL + "/users", {
      params: posts.map(p => p.author_id)
    }).then(users => {
      dispatch({ type: "FETCH_POSTS", payload: {
          posts, users
      }})
    })
  )
}

Don't forget about the try/catch syntax as well. You can try/catch entire blocks of code, and then dispatch an error as well. In the later case (Not using async/await), you would need to chain the .then()'s into 2 separate error handlers.

Upvotes: 1

Related Questions