or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-lit--task

A controller for Lit that renders asynchronous tasks.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@lit/task@1.0.x

To install, run

npx @tessl/cli install tessl/npm-lit--task@1.0.0

0

# @lit/task

1

2

@lit/task is a reactive controller for Lit elements that simplifies the management and rendering of asynchronous tasks such as API calls, data fetching, and remote operations. It provides automatic task execution when arguments change, manual task control, comprehensive status tracking (INITIAL, PENDING, COMPLETE, ERROR), and built-in rendering patterns for different task states.

3

4

## Package Information

5

6

- **Package Name**: @lit/task

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @lit/task`

10

11

## Core Imports

12

13

```typescript

14

import { Task, TaskStatus } from "@lit/task";

15

```

16

17

For deep equality utilities:

18

19

```typescript

20

import { deepArrayEquals, deepEquals } from "@lit/task/deep-equals.js";

21

```

22

23

For direct task module access:

24

25

```typescript

26

import { Task, TaskStatus, shallowArrayEquals, initialState } from "@lit/task/task.js";

27

```

28

29

## Basic Usage

30

31

```typescript

32

import { LitElement, html } from "lit";

33

import { state } from "lit/decorators.js";

34

import { Task, TaskStatus } from "@lit/task";

35

36

class MyElement extends LitElement {

37

@state()

38

private _userId: number = -1;

39

40

private _apiTask = new Task(

41

this,

42

async ([userId], { signal }) => {

43

const response = await fetch(`/api/users/${userId}`, { signal });

44

if (!response.ok) {

45

throw new Error(`HTTP ${response.status}: ${response.statusText}`);

46

}

47

return response.json();

48

},

49

() => [this._userId]

50

);

51

52

render() {

53

return html`

54

<div>User Info</div>

55

${this._apiTask.render({

56

pending: () => html`<p>Loading user info...</p>`,

57

complete: (user) => html`<p>Name: ${user.name}</p>`,

58

error: (error) => html`<p>Error: ${error.message}</p>`

59

})}

60

`;

61

}

62

}

63

```

64

65

## Architecture

66

67

@lit/task is built around several key components:

68

69

- **Task Controller**: Main `Task` class that integrates with Lit's reactive update cycle

70

- **Status Management**: Built-in state tracking through `TaskStatus` constants

71

- **Argument Tracking**: Automatic detection of argument changes to trigger task re-execution

72

- **Abort Control**: Built-in AbortSignal support for cancelling pending operations

73

- **Rendering Integration**: Template rendering methods that respond to task state changes

74

- **Equality Functions**: Customizable argument comparison for fine-grained control over when tasks run

75

76

## Capabilities

77

78

### Task Management

79

80

Core task execution and lifecycle management functionality for creating, running, and controlling asynchronous operations in Lit elements.

81

82

```typescript { .api }

83

class Task<T extends ReadonlyArray<unknown>, R> {

84

constructor(host: ReactiveControllerHost, config: TaskConfig<T, R>);

85

constructor(

86

host: ReactiveControllerHost,

87

task: TaskFunction<T, R>,

88

args?: ArgsFunction<T>

89

);

90

}

91

92

interface TaskConfig<T, R> {

93

task: TaskFunction<T, R>;

94

args?: ArgsFunction<T>;

95

autoRun?: boolean | 'afterUpdate';

96

argsEqual?: (oldArgs: T, newArgs: T) => boolean;

97

initialValue?: R;

98

onComplete?: (value: R) => unknown;

99

onError?: (error: unknown) => unknown;

100

}

101

```

102

103

[Task Management](./task-management.md)

104

105

### Status and Rendering

106

107

Task status tracking and template rendering functionality for displaying different task states with appropriate UI feedback.

108

109

```typescript { .api }

110

const TaskStatus = {

111

INITIAL: 0,

112

PENDING: 1,

113

COMPLETE: 2,

114

ERROR: 3,

115

} as const;

116

117

interface StatusRenderer<R> {

118

initial?: () => unknown;

119

pending?: () => unknown;

120

complete?: (value: R) => unknown;

121

error?: (error: unknown) => unknown;

122

}

123

```

124

125

[Status and Rendering](./status-rendering.md)

126

127

### Argument Equality

128

129

Argument comparison utilities for controlling when tasks should re-execute based on changes to their input parameters.

130

131

```typescript { .api }

132

function shallowArrayEquals<T>(oldArgs: T, newArgs: T): boolean;

133

function deepArrayEquals<T>(oldArgs: T, newArgs: T): boolean;

134

function deepEquals(a: unknown, b: unknown): boolean;

135

```

136

137

[Argument Equality](./argument-equality.md)

138

139

## Types

140

141

```typescript { .api }

142

type TaskFunction<D extends ReadonlyArray<unknown>, R = unknown> = (

143

args: D,

144

options: TaskFunctionOptions

145

) => R | typeof initialState | Promise<R | typeof initialState>;

146

147

type ArgsFunction<D extends ReadonlyArray<unknown>> = () => D;

148

149

type DepsFunction<D extends ReadonlyArray<unknown>> = ArgsFunction<D>;

150

151

interface TaskFunctionOptions {

152

signal: AbortSignal;

153

}

154

155

type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus];

156

157

const initialState: unique symbol;

158

159

type MaybeReturnType<F> = F extends (...args: never[]) => infer R

160

? R

161

: undefined;

162

```