Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Action Creator and Action Type Naming Convention?

Tags:

reactjs

redux

Are there any official naming convention on naming action creators and action.types

Looking over tutorials the theme of the action creator and action type is to name the action type pretty much one to one with action creator.

To use an example lets say we have an application fetching blog posts

The tutorial (top rated Udemy tutorial) used the following naming convention with asynchronous action creator:

export const fetchPosts = () => async dispatch => {
    const response = await postsAPI.get('/posts');

    dispatch({type: 'FETCH_POSTS', payload: response.data});
};

However, wouldnt it make more sense to name the action objects more precisely (to signify success or failure) to what is being dispatched. Rather than matching action creator function name with action type, along the lines of:

export const fetchPosts = () => async dispatch => {
    const response = await postsAPI.get('/posts');
    
    if (response.status === 200) {
       dispatch({type: 'FETCHED_POSTS', payload: response.data});
    } else {
        dispatch({type: 'FAILED_TO_FETCH_POSTS', payload: response});
    }
};
like image 330
user7858768 Avatar asked Nov 08 '25 10:11

user7858768


1 Answers

Yes, the official style guides suggests to write action types as domain/eventname.

This goes along with a few other things from the style guide.

  • the recommendation to use redux toolkit instead of writing redux logic by hand, which allows you to create slices, which will automatically prefix all action names for a slice. (Also, you'll no longer need to write action types, action creators, switch-case statements or immutable logic by hand as RTK does that for you, see modern redux)
  • the recommendation to organize your files by feature
  • the recommendation to model actions as events
  • the recommendation to write meaningful action names

Adding to that, I prefer my actions to be in the past like todos/added when they describe something that happened in the application or something the user did, and to be in the imperative like todos/save when they describe a side effect that should be handled in a middleware (which will then maybe do an API request and end up in a todos/saved action to actually lead to changes in a reducer).

A few more things are implicitly done by RTK, for example createAsyncThunk will autmatically create three actions for every thunk: yourActionPrefix/pending, yourActionPrefix/fulfilled and yourActionPrefix/rejected.

like image 76
phry Avatar answered Nov 11 '25 05:11

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!