This package defines finite number of data status and helps automatically define which of statuses are states in
export enum DataStatus {
Loaded = "Loaded",
Loading = "Loading",
Error = "Error",
Empty = "Empty",
Denied = "Denied",
Modified = "Modified",
}
Also has interface gathering some informations about what happened with data like last time is was succesfully saved on server and last error
export interface DataUnit<T> {
data: T | null;
status: DataStatus;
timestamp?: string;
error?: Error;
}
export interface IDetails {
a: string;
b: string;
}
@State<DataUnit<IDetails>>({
name: 'single',
defaults: {
status: DataStatus.Empty,
data: null,
},
})
@Injectable()
export class DetailsState {
@Selector()
static getData(state: DataUnit<IDetails): IDetails {
return state.data;
}
@Selector()
static getStatus(state: DataUnit<IDetails): DataStatus {
return state.status;
}
constructor(private service: DetailsService) {}
@Action(Load)
load(ctx: StateContext<DataUnit<IDetails>>) {
startLoad(ctx);
return this.service.load().pipe(operate(ctx, load));
}
}
export interface User {
name: string;
age: number;
}
export interface IComplexState {
a: string;
complexObject: {
myFancyData: DataUnit<User[]>;
};
simpleData: DataUnit<User>;
}
@State<IComplexState>({
name: 'complex',
defaults: {
a: string;
complexObject: {
myFancyData: {
status: DataStatus.Empty,
data: [],
},
};
simpleData: {
status: DataStatus.Empty,
data: null,
},
}
})
@Injectable()
export class DetailsState {
@Selector()
static getUsersList(state: IComplexState): DataUnit<User[]> {
return state.complexObject.myFancyData;
}
@Selector()
static getUser(state: IComplexState): DataUnit<User> {
return state.simpleData;
}
constructor(private service: UserService) {}
@Action(LoadSimpleData)
loadSimpleData(ctx: StateContext<IComplexState>) {
startLoad(ctx, 'simpleData');
return this.service.loadUser().pipe(operate(ctx, load, 'simpleData'));
}
@Action(LoadComplexData)
loadComplexData(ctx: StateContext<IComplexState>) {
startLoad(ctx, 'complexObject.myFancyData');
return this.service.loadUsersList().pipe(operate(ctx, load, 'complexObject.myFancyData'));
}
@Action(UpdateUser)
updateUser(ctx: StateContext<IComplexState>) {
startLoad(ctx, 'complexObject.myFancyData');
return this.service.updateUserName(ctx.getState().a).pipe(operate(ctx, save, 'simpleData'));
}
}