Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I should set redux actions type with an exported constants?

I'm trying to learn react with redux, I've read in the main documentation of redux, we should store actions types into one js files and then export all constants and use them into type, for example it's simple mode:

export function itemsAction(items) {
    return {
        type: 'ITEMS',
        data: items
    }
}

But apparently I should do in this format:

import { types } from './Types';

export function itemsAction(items) {
    return {
        type: types.ITEMS,
        data: items
    }
}

But what's the main benefit of this trick? actions are fixed and never changes, why I should set the action types from variables and import all types ?

Thanks

like image 926
Alex Avatar asked Jan 01 '23 22:01

Alex


1 Answers

Because it's good to know you're using an object property rather than a raw string, since raw strings are prone to typos. Take your example:

export function itemsAction(items) {
    return {
        type: 'ITEMS',
        data: items
    }
}

Now let's say I have a reducer to handle that action that also uses a raw string:

const todos = (state = [], action) => {
  switch (action.type) {
    case 'ITESM':
      return state.map(item => item.something = "potato")
    default:
      return state
  }
}

In the reducer, I misspelled the action type for its case. But due to how Javascript and Redux work, it won't get noticed as an error in your IDE linting, nor will it produce any errors when you execute the code. You'll dispatch the action, and it will silently fail. Nothing will happen, no action, no errors, nothing. This can be a pain to debug.

In addition, what if you want to change the name of an action. It's good to just go change the value in the object, rather than do a big find and replace across your whole project, hoping you don't overwrite something you didn't mean to in the process.

Plus it's just nice to have all your action types in one place, so you can go through and see what you have available, rather than looking through all your action files. Once your project grows, you'll be glad you did it.

Also, on Typescript it's especially useful, since if you try to use an action you haven't defined it won't even build, so you get some build time safety.

like image 126
Jayce444 Avatar answered Jan 03 '23 12:01

Jayce444