From 01fbb020a301152ff2e0b5b12c98acaa368d6c84 Mon Sep 17 00:00:00 2001 From: BrainCrumbz Date: Sat, 16 Nov 2024 04:29:46 +0100 Subject: [PATCH] chore(lit): fetch data, extract function to create task in a separate file (#279) Co-authored-by: Giuseppe Piscopo --- .../2-fetch-data/lit/fetch-users-task.js | 14 ++++++++++++++ .../7-webapp-features/2-fetch-data/lit/x-app.js | 13 ++----------- 2 files changed, 16 insertions(+), 11 deletions(-) create mode 100644 content/7-webapp-features/2-fetch-data/lit/fetch-users-task.js diff --git a/content/7-webapp-features/2-fetch-data/lit/fetch-users-task.js b/content/7-webapp-features/2-fetch-data/lit/fetch-users-task.js new file mode 100644 index 00000000..c2f2457f --- /dev/null +++ b/content/7-webapp-features/2-fetch-data/lit/fetch-users-task.js @@ -0,0 +1,14 @@ +import { Task } from "@lit/task"; + +export function createFetchUsersTask(element) { + return new Task(element, { + task: async () => { + const response = await fetch("https://randomuser.me/api/?results=3"); + if (!response.ok) { + throw new Error(response.status); + } + return response.json(); + }, + args: () => [], + }); +} diff --git a/content/7-webapp-features/2-fetch-data/lit/x-app.js b/content/7-webapp-features/2-fetch-data/lit/x-app.js index 79e6e92b..0ed628e8 100644 --- a/content/7-webapp-features/2-fetch-data/lit/x-app.js +++ b/content/7-webapp-features/2-fetch-data/lit/x-app.js @@ -1,19 +1,10 @@ -import { Task } from "@lit/task"; import { LitElement, html } from "lit"; import { customElement } from "lit/decorators.js"; +import { createFetchUsersTask } from "./fetch-users-task"; @customElement("x-app") export class XApp extends LitElement { - fetchUsers = new Task(this, { - task: async () => { - const response = await fetch("https://randomuser.me/api/?results=3"); - if (!response.ok) { - throw new Error(response.status); - } - return response.json(); - }, - args: () => [], - }); + fetchUsers = createFetchUsersTask(this); render() { return this.fetchUsers.render({