In my react application, I have to use several enums. How should I structure them in my application? What I have done is, I created enums.js file under my config folder, and set enums like this.
export const USER_TYPES = {
USER: "user",
TRAINER: "trainer",
ADMIN: "admin"
}
export const USER_STATUS = {
FOLLOW: "Follow",
REQUESTED: "Requested",
FOLLOWING: "Following"
}
export const FOLLOWING_STATUS = {
FOLLOW: -1,
REQUESTED: 0,
FOLLOWING: 1
}
Is this a good way of doing this?
In the App. js file, we will create an enum object first. After that, we will add an 'enum' function to render components according to state value. At last, we will edit the 'App' component and call the 'enum' function inside the component to render it conditionally.
An enum is a great way to have multiple conditional renderings. Let's consider the notification component again, this time we can use the enum as inlined object. The state property key helps us to retrieve the value from the object. It is much more readable compared to the switch case operator.
Enum Values The first member of an enum will be 0, and the value of each successive enum member is increased by 1.
It also generates the problem of runtime overhead and your app will required more space. So overuse of ENUM in Android would increase DEX size and increase runtime memory allocation size. If your application is using more ENUM then better to use Integer or String constants instead of ENUM.
For a more semantic use, you could rename and move your file from config/enum.js
to constants/users.js
.
There you export each object your want, but with a shortened name:
USER_TYPE
-> TYPES
, USER_STATUS
-> STATUS
.
So when you import your file you can do: import * as USERS from 'constants/users;
and use it like this: USERS.STATUS.FOLLOW
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With