matschik / component-party.dev

🎉 Web component JS frameworks overview by their syntax and features
https://component-party.dev
MIT License
2.7k stars 236 forks source link

Proposal: in Lit fetch data use case move function to another file #277

Open BrainCrumbz opened 5 hours ago

BrainCrumbz commented 5 hours ago

To ease comparison in this use case, e.g. between Svelte 5 and Lit, one could move the Lit fetching responsibility to another file, in the same way as Svelte example does. So current Lit component:

<<omitted>>
  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: () => [],
  });
<<omitted>>

would become something like:

import { createFetchUsersTask } from "./fetch-users.js";
<<omitted>>
  fetchUsers = createFetchUsersTask(this);
<<omitted>>

and a new fetch-users.js file like the following would be added:

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: () => [],
  });
}

Sorry for any error, this has been written without any IDE support.

In this way, one could more easily compare both the component invoking the fetch functionality, as well as the utility implementing that functionality, given that both of them differ.

matschik commented 3 hours ago

To be iso with other framework snippet, I think it's a great idea ! I'm looking forward for your PR