State management in front-end application

You can find plenty of examples showing how state management libraries work, few people focus on it why do we need state management and what problems does it cause (solve?). In this article I will walk you through, step by step, what common application state issues might look like applications and how to deal with them regardless of whether you use because it doesn't matter what you use, only for what purpose.

December 5, 2023 angularangular-17typescript

You can view the source code for this project by following this link: GitHub

Loading state

Imagine a situation where you have to send a request to a server to get data. This operation can take some time so it can be a good idea to display a spinner with some text to inform a user that something is happening (instead of displaying a blank page). To do this we can create a variable loading and write in our template logic to display one of two views: loading view or data view.

1
export class ExampleComponent {
2
private toDos$ = inject(TodoService).getToDos({ limit: 3 });
3
4
loading = true;
5
toDos: ToDo[] = [];
6
7
constructor() {
8
this.toDos$.subscribe((toDos) => {
9
this.toDos = toDos;
10
this.loading = false;
11
});
12
}
13
}
1
if (loading) {
2
<p>Spinner</p>;
3
} else {
4
<table> ... </table>;
5
}

More states

In a real scenario, we have more than just two states. When we display some data we want to allow users to filter, sort or paginate it. In this case, it would be nice to display some kind of spinner when data are updating. But what about errors? A server can also respond with a temporary issue (no connection to the database, internal server error, or timeout). It also would be nice to display.

Similar to before, we can do this by adding new variables to our view: error and refreshing. But this does not cover all needs. We also want to store data about the error and also items to display. This makes our component bigger and less readable.

1
export class DataToDisplay {
2
private toDos$ = inject(TodoService).getToDos({ limit: 3 });
3
4
loading = true;
5
refreshing = false;
6
error = false;
7
toDos: ToDo[] = [];
8
errorData: Error | null = null;
9
10
constructor() {
11
this.loadToDos();
12
}
13
14
refresh() {
15
this.refreshing = true;
16
this.loadToDos();
17
}
18
19
private loadToDos() {
20
this.toDos$.subscribe({
21
next: (toDos) => {
22
this.loading = false;
23
this.refreshing = false;
24
this.error = false;
25
this.toDos = toDos;
26
},
27
error: (error) => {
28
this.error = true;
29
this.loading = false;
30
this.refreshing = false;
31
this.errorData = error;
32
},
33
});
34
}
35
}
1
if (loading) {
2
<p>Spinner</p>;
3
} else if (error) {
4
<p>Something bad happened</p>;
5
} else {
6
<table>...</table>;
7
if (refreshing) {
8
<p>Inner spinner</p>;
9
}
10
}

State object

To resolve described problems with too many variables we can create something that is called state object. This pattern is about creating a plan JavaScript object and storing all data needed to display the view in a single object.

1
export interface ComponentState {
2
readonly loading: boolean;
3
readonly refreshing: boolean;
4
readonly toDos: Item[];
5
readonly error: boolean;
6
readonly errorData: Error | null;
7
}
8
9
const INITIAL_STATE: ComponentState = {
10
loading: true,
11
refreshing: false,
12
toDos: [],
13
error: false,
14
errorData: null,
15
} as const;

readonly is necessary to block possibility to mutate a state.

Now we can come back to our component and replace all properties with single-state objects. Thanks to that our component is more readable.

1
export class DataToDisplay {
2
private toDos$ = inject(TodoService).getToDos({ limit: 3 });
3
4
state = getInitialState();
5
6
constructor() {
7
this.loadToDos();
8
}
9
10
refresh() {
11
this.state = {
12
loading: false,
13
refreshing: true,
14
error: false,
15
errorData: null,
16
toDos: this.state.toDos,
17
};
18
this.loadToDos();
19
}
20
21
private loadToDos() {
22
this.toDos$.subscribe({
23
next: (toDos) => {
24
this.state = {
25
loading: false,
26
refreshing: false,
27
error: false,
28
errorData: null,
29
toDos: toDos,
30
};
31
},
32
error: (error) => {
33
this.state = {
34
loading: false,
35
refreshing: false,
36
error: true,
37
errorData: error,
38
toDos: [],
39
};
40
},
41
});
42
}
43
}

Problem with types

Imagine a situation where we want to create an effect to log an error message. When an error occurs we want to get the errorData property.

1
export function errorCountEffect(state: ComponentState): void {
2
if (state.error === true) {
3
const type = state.errorData?.message; // I had to add `?` because `errorData` can be null
4
// ...
5
}
6
}

We should not have a situation where error is set as true but errorData is null.

1
const type = state.errorData!.message;

TypeScript will throw an error errorData is possibly null only when you have strictNullChecks or strict flag turned on.

Union states

In a situation where we know that error and errorData properties are connected (when error is false then errorData is null and when error is true then errorData is defined) we can create interfaces for each state and connect them with Union types.

1
export interface NoErrorState {
2
loading: boolean;
3
refreshing: boolean;
4
toDos: ToDo[];
5
error: false;
6
errorData: null;
7
}
8
9
export interface ErrorState {
10
loading: boolean;
11
refreshing: boolean;
12
toDos: ToDo[];
13
error: true;
14
errorData: Error;
15
}
16
17
export type ComponentState = NoErrorState | ErrorState;

Thanks to that separation, we tell TypeScript that ComponentState is one of two states: NoErrorState or ErrorState and TypeScript will know when error is true then errorData is defined.

1
export function errorCountEffect(state: ComponentState): void {
2
if (state.error === true) {
3
const type = state.errorData.message; // There is no error now! No need to add `?`.
4
5
// ...
6
}
7
}

TypeScript knows that when error is true then state inside if block has type ErrorState (TS Playground).

Split into more states

When we know that we can create many states and connect them into a single type we can define all possible states with interfaces.

1
interface LoadingState {
2
loading: true;
3
}
4
5
interface LoadedState {
6
toDos: ToDo[];
7
}
8
9
interface RefreshingState {
10
refreshing: true;
11
toDos: ToDo[];
12
}
13
14
interface ErrorState {
15
error: true;
16
errorData: Error;
17
}
18
19
export type ComponentState = LoadingState | LoadedState | RefreshingState | ErrorState;

Checking current state

Let us go back to our effect where we want to check current state. To do this we have to check which properties are defined and which are not.

1
export function errorCountEffect(state: ComponentState): void {
2
if ("error" in state) {
3
const message = state.errorData.message;
4
// ...
5
}
6
}

This if statement is not readable and each time we have to know what to check.

Keyword in is used as a type guard. Because only LoadedState has data property TypeScript knows that inside if variable currentState have to be LoadedState (TS Playground).

Named states

To make easier checking current state we can create a special property which will hold current state name.

1
export interface LoadingState {
2
name: "LOADING";
3
}
4
5
export interface LoadedState {
6
name: "LOADED";
7
toDos: ToDo[];
8
}
9
10
export interface RefreshingState {
11
name: "REFRESHING";
12
toDos: ToDo[];
13
}
14
15
export interface ErrorState {
16
name: "ERROR";
17
error: Error;
18
}
19
20
export type ComponentState = LoadingState | LoadedState | RefreshingState | ErrorState;

We can create a interface to share base properties. This is nice to have but not required.

1
interface State<T> {
2
name: T;
3
}
4
5
export interface LoadedState extends State<"LOADED"> {
6
toDos: ToDo[];
7
}

Now we can refactor the previous function and use simple checking of name property (TS Playground).

1
export function errorCountEffect(state: ComponentState): void {
2
if (state.name === "ERROR") {
3
const message = state.errorData.message;
4
// ...
5
}
6
}

Comparing writing templates

Let us come back to our templates from the beginning. When we had individual properties for each state our template looks like below.

1
if (loading) {
2
<p>Spinner</p>;
3
} else if (error) {
4
<p>Something bad happened</p>;
5
} else {
6
<table>...</table>;
7
if (refreshing) {
8
<p>Inner spinner</p>;
9
}
10
}

But when we migrated to the named states the template has to change. We cannot look now for individual properties. We have to now write a template where we will check a current state and for each state we need to have a template.

1
switch (state.name) {
2
case "LOADING":
3
<p>Spinner</p>;
4
break;
5
case "LOADED":
6
<table> ... </table>;
7
break;
8
case "REFRESHING":
9
<table> ... </table>;
10
<p>Inner spinner</p>;
11
break;
12
default:
13
<p>Unknown state</p>;
14
break;
15
}

We can also handle many states at single case. It approach will be helpful where two states have a very similar look.

1
switch (state.name) {
2
case "LOADING":
3
<p>Spinner</p>;
4
break;
5
case "LOADED":
6
case "REFRESHING":
7
<table> ... </table>;
8
if (state.state === "REFRESHING") {
9
<p>Inner spinner</p>;
10
}
11
break;
12
default:
13
<p>Unknown state</p>;
14
break;
15
}

Comparing changing state

When we take a loot into the code from the beginning we can see that we had to “reset” each property one by one. It it very easy to make a mistake and forget to change a variable to original value.

1
let loading = true;
2
let refreshing = false;
3
let error = false;
4
let toDos: ToDo[] = [];
5
let errorData: Error | null = null;
6
7
this.toDos$.subscribe({
8
next: (toDos) => {
9
this.loading = false;
10
this.refreshing = false;
11
this.error = false;
12
this.toDos = toDos;
13
},
14
error: (error) => {
15
this.error = true;
16
this.loading = false;
17
this.refreshing = false;
18
this.errorData = error;
19
},
20
});

In situation where we will use named states the code is much more shorter and most important more readable.

1
let state: ComponentState = { name: "LOADING" };
2
3
this.toDos$.subscribe({
4
next: (toDos) => {
5
state = { name: "LOADED", data: toDos };
6
},
7
error: (error) => {
8
state = { name: "ERROR", error: error };
9
},
10
});

Final version

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment