or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-loading.mdbuilding.mdcomponents.mdindex.mdoffline.mdstorage.md
tile.json

api-loading.mddocs/

0

# API Loading

1

2

Functions for loading icon data from the Iconify API, including batch loading, custom providers, and custom loaders. The API system automatically handles icon loading when components request unknown icons.

3

4

## Capabilities

5

6

### Load Multiple Icons

7

8

Load multiple icons in a single API request with a callback when loading completes.

9

10

```typescript { .api }

11

/**

12

* Load multiple icons from API

13

* @param icons - Array of icon names to load

14

* @param callback - Optional callback when loading completes

15

* @returns Function to abort the loading operation

16

*/

17

function loadIcons(

18

icons: string[],

19

callback?: IconifyIconLoaderCallback

20

): IconifyIconLoaderAbort;

21

22

type IconifyIconLoaderCallback = (

23

loaded: IconifyIconName[],

24

missing: IconifyIconName[],

25

pending: IconifyIconName[]

26

) => void;

27

28

type IconifyIconLoaderAbort = () => void;

29

30

interface IconifyIconName {

31

provider: string;

32

prefix: string;

33

name: string;

34

}

35

```

36

37

**Usage Examples:**

38

39

```typescript

40

import { loadIcons } from "@iconify/react";

41

42

// Load icons without callback

43

const abort = loadIcons([

44

"mdi:home",

45

"mdi:account",

46

"mdi:settings"

47

]);

48

49

// Load icons with callback

50

loadIcons([

51

"mdi:home",

52

"mdi:account",

53

"mdi:settings"

54

], (loaded, missing, pending) => {

55

console.log("Loaded icons:", loaded);

56

console.log("Missing icons:", missing);

57

console.log("Still pending:", pending);

58

59

// All requested icons are now available

60

if (missing.length === 0 && pending.length === 0) {

61

console.log("All icons loaded successfully");

62

}

63

});

64

65

// Load icons and abort if needed

66

const abortLoading = loadIcons(["mdi:home", "mdi:account"]);

67

68

// Cancel loading after 5 seconds

69

setTimeout(() => {

70

abortLoading();

71

console.log("Loading cancelled");

72

}, 5000);

73

74

// Load from different providers

75

loadIcons([

76

"@custom-provider:icons:home",

77

"@another-provider:ui:button",

78

"mdi:default-provider-icon"

79

]);

80

```

81

82

### Load Single Icon (Promise)

83

84

Load a single icon and return a Promise that resolves with the icon data.

85

86

```typescript { .api }

87

/**

88

* Load single icon from API using Promise

89

* @param icon - Icon name to load

90

* @returns Promise that resolves with icon data or rejects if not found

91

*/

92

function loadIcon(icon: string): Promise<IconifyIcon>;

93

```

94

95

**Usage Examples:**

96

97

```typescript

98

import { loadIcon } from "@iconify/react";

99

100

// Load single icon with Promise

101

try {

102

const iconData = await loadIcon("mdi:home");

103

console.log("Icon loaded:", iconData);

104

// Use iconData directly: <Icon icon={iconData} />

105

} catch (error) {

106

console.error("Failed to load icon:", error);

107

}

108

109

// Load icon in React component

110

function MyComponent() {

111

const [iconData, setIconData] = useState(null);

112

const [loading, setLoading] = useState(true);

113

114

useEffect(() => {

115

loadIcon("mdi:home")

116

.then(data => {

117

setIconData(data);

118

setLoading(false);

119

})

120

.catch(error => {

121

console.error("Icon load failed:", error);

122

setLoading(false);

123

});

124

}, []);

125

126

if (loading) return <div>Loading icon...</div>;

127

128

return iconData ? <Icon icon={iconData} /> : <div>Icon not found</div>;

129

}

130

131

// Load multiple icons with Promise.all

132

async function loadMultipleIcons() {

133

try {

134

const icons = await Promise.all([

135

loadIcon("mdi:home"),

136

loadIcon("mdi:account"),

137

loadIcon("mdi:settings")

138

]);

139

140

console.log("All icons loaded:", icons);

141

return icons;

142

} catch (error) {

143

console.error("Failed to load some icons:", error);

144

}

145

}

146

```

147

148

### Add API Provider

149

150

Configure custom API providers for loading icons from different sources.

151

152

```typescript { .api }

153

/**

154

* Add custom API provider

155

* @param provider - Provider identifier

156

* @param config - Provider configuration

157

* @returns true if provider was added successfully, false on error

158

*/

159

function addAPIProvider(

160

provider: string,

161

config: PartialIconifyAPIConfig

162

): boolean;

163

164

interface PartialIconifyAPIConfig {

165

/** Array of API resource URLs */

166

resources: string[];

167

168

/** Index of current resource (for rotation) */

169

index?: number;

170

171

/** Request timeout in milliseconds */

172

timeout?: number;

173

174

/** Rotate resources after each request */

175

rotate?: number;

176

177

/** Use random resource instead of rotation */

178

random?: boolean;

179

180

/** Allow data after timeout */

181

dataAfterTimeout?: boolean;

182

}

183

```

184

185

**Usage Examples:**

186

187

```typescript

188

import { addAPIProvider } from "@iconify/react";

189

190

// Add custom API provider

191

const success = addAPIProvider("my-company", {

192

resources: [

193

"https://api.mycompany.com/icons",

194

"https://backup-api.mycompany.com/icons"

195

],

196

timeout: 5000,

197

rotate: 1 // Rotate to next resource after each request

198

});

199

200

if (success) {

201

console.log("Custom provider added");

202

// Now can use: <Icon icon="@my-company:icons:logo" />

203

}

204

205

// Add provider with multiple resources for redundancy

206

addAPIProvider("enterprise", {

207

resources: [

208

"https://icons-api-1.enterprise.com/v1",

209

"https://icons-api-2.enterprise.com/v1",

210

"https://icons-api-3.enterprise.com/v1"

211

],

212

timeout: 3000,

213

random: true, // Use random resource for load balancing

214

dataAfterTimeout: true // Accept data even if it arrives after timeout

215

});

216

217

// Load icons from custom provider

218

loadIcons(["@my-company:brand:logo", "@enterprise:ui:dashboard"]);

219

```

220

221

### Custom Icon Loaders

222

223

Set custom functions for loading icons when they're not found through normal API calls.

224

225

```typescript { .api }

226

/**

227

* Set custom icon loader function

228

* @param loader - Function to load single icon

229

*/

230

function setCustomIconLoader(loader: IconifyCustomIconLoader): void;

231

232

/**

233

* Set custom icons loader function for batch loading

234

* @param loader - Function to load multiple icons

235

*/

236

function setCustomIconsLoader(loader: IconifyCustomIconsLoader): void;

237

238

type IconifyCustomIconLoader = (

239

name: string,

240

prefix: string,

241

provider: string

242

) => Promise<IconifyIcon | null>;

243

244

type IconifyCustomIconsLoader = (

245

names: string[],

246

prefix: string,

247

provider: string

248

) => Promise<(IconifyIcon | null)[]>;

249

```

250

251

**Usage Examples:**

252

253

```typescript

254

import { setCustomIconLoader, setCustomIconsLoader } from "@iconify/react";

255

256

// Set custom single icon loader

257

setCustomIconLoader(async (name, prefix, provider) => {

258

console.log(`Loading icon: ${name} from ${prefix} (provider: ${provider})`);

259

260

try {

261

// Custom loading logic - fetch from your API

262

const response = await fetch(`/api/icons/${prefix}/${name}`);

263

if (!response.ok) return null;

264

265

const iconData = await response.json();

266

return iconData;

267

} catch (error) {

268

console.error("Custom loader failed:", error);

269

return null;

270

}

271

});

272

273

// Set custom batch loader for better performance

274

setCustomIconsLoader(async (names, prefix, provider) => {

275

console.log(`Batch loading ${names.length} icons from ${prefix}`);

276

277

try {

278

// Batch request to your API

279

const response = await fetch(`/api/icons/${prefix}`, {

280

method: 'POST',

281

headers: { 'Content-Type': 'application/json' },

282

body: JSON.stringify({ icons: names })

283

});

284

285

if (!response.ok) return names.map(() => null);

286

287

const data = await response.json();

288

return names.map(name => data[name] || null);

289

} catch (error) {

290

console.error("Custom batch loader failed:", error);

291

return names.map(() => null);

292

}

293

});

294

295

// Custom loader for database icons

296

setCustomIconLoader(async (name, prefix, provider) => {

297

if (prefix !== "db-icons") return null;

298

299

try {

300

const iconRecord = await db.icons.findOne({ name });

301

if (!iconRecord) return null;

302

303

return {

304

body: iconRecord.svg_content,

305

width: iconRecord.width || 24,

306

height: iconRecord.height || 24

307

};

308

} catch (error) {

309

console.error("Database loader failed:", error);

310

return null;

311

}

312

});

313

```

314

315

### Advanced Loading Configuration

316

317

Configure global API behavior and monitoring.

318

319

```typescript

320

import { addAPIProvider, loadIcons, _api } from "@iconify/react";

321

322

// Get API configuration

323

const config = _api.getAPIConfig(""); // Empty string for default provider

324

console.log("Default API config:", config);

325

326

// List all available providers

327

const providers = _api.listAPIProviders();

328

console.log("Available providers:", providers);

329

330

// Configure custom fetch function (for Node.js or custom HTTP handling)

331

_api.setFetch(async (url, options) => {

332

console.log("Custom fetch:", url);

333

334

// Use custom fetch implementation

335

const response = await fetch(url, {

336

...options,

337

headers: {

338

...options?.headers,

339

'User-Agent': 'MyApp/1.0'

340

}

341

});

342

343

return response;

344

});

345

346

// Monitor icon loading

347

loadIcons(["mdi:home", "mdi:account"], (loaded, missing, pending) => {

348

console.log("Loading status:");

349

console.log("- Loaded:", loaded.map(icon => `${icon.prefix}:${icon.name}`));

350

console.log("- Missing:", missing.map(icon => `${icon.prefix}:${icon.name}`));

351

console.log("- Pending:", pending.map(icon => `${icon.prefix}:${icon.name}`));

352

});

353

```

354

355

### Error Handling

356

357

Handle various loading scenarios and errors.

358

359

```typescript

360

import { loadIcon, loadIcons } from "@iconify/react";

361

362

// Handle Promise rejection

363

async function safeLoadIcon(name: string) {

364

try {

365

const icon = await loadIcon(name);

366

return icon;

367

} catch (error) {

368

console.warn(`Failed to load icon "${name}":`, error);

369

return null; // Return null instead of throwing

370

}

371

}

372

373

// Handle callback errors

374

loadIcons(["mdi:home", "nonexistent:icon"], (loaded, missing, pending) => {

375

if (missing.length > 0) {

376

console.warn("Some icons could not be loaded:", missing);

377

378

// Provide fallback behavior

379

missing.forEach(icon => {

380

console.log(`Missing icon: ${icon.prefix}:${icon.name}`);

381

});

382

}

383

384

if (loaded.length > 0) {

385

console.log("Successfully loaded:", loaded);

386

}

387

});

388

389

// Timeout handling

390

const abortController = new AbortController();

391

392

// Set timeout for loading

393

setTimeout(() => {

394

abortController.abort();

395

console.log("Icon loading timed out");

396

}, 10000);

397

398

// Note: AbortController integration depends on custom loader implementation

399

```