I've been looking at examples for setting up boilerplate for ngrx entity and was curious why most people set up their model with string type id. It's strange because for the EntityState, the selected id is then stored as a number. For the most part, examples I've seen use this but I haven't been able to find a rational.
What are the benefits of this? I was thinking possibly for easy JSON encoding but this makes normal operations like incrementing index and lookups annoying. Would rather just encode when the data needs to be exported.
Here's a link to the example on the official repo: https://github.com/ngrx/platform/blob/master/docs/entity/adapter.md
export interface User {
id: string;
name: string;
}
export interface State extends EntityState<User> {
// additional entities state properties
selectedUserId: number | null;
}
export const initialState: State = adapter.getInitialState({
// additional entity state properties
selectedUserId: null,
});
I believe that within the example: selectedUserId: number | null;
is an error as they later define a user as:
export interface User {
id: string;
name: string;
}
That said, why use string rather than numbers?
1) I guess for a better global support. If people are using database with IDs stored as numbers, then fine you can just save them as string without any issue. But if it was a string, it'd be harder to save it as a number...
2) (and real argument here) a lot of people are using UUID to generate some IDs directly from the frontend. It allows you to ensure that an ID will be unique* even if generated from the frontend and thus, you can work offline (creating a resource and still work with it before synchronizing with the backend), which would be very much harder otherwise.
Even if you're not planning to support offline mode within your app, there's a more common use case I think: Optimistic update. So you generate an ID for your resource, save your resource in your REDUX store or wherever you want to save it, then make a request to add it into the backend for ex. If everything is fine, then ok! Otherwise, just display a message few seconds later saying that the resource couldn't be saved an eventually propose to retry. But every time where this will be working, the user will be pleased to have an instant interaction with your app, not feeling any "lags" because of the network.
*: it's not 100% guaranteed but if you read articles about UUID, the chances to generate an already existing one are very, very, very low. Plus, you can still make some check on the backend that on a POST the ID doesn't exist, etc.