component-party.dev icon indicating copy to clipboard operation
component-party.dev copied to clipboard

Update App.svelte by destructuring of an Object

Open RajuPedda opened this issue 1 year ago • 5 comments

Destructured the response object to have a better comparison with other frameworks / libraries as the others also does the same destructuring.

RajuPedda avatar Sep 25 '24 04:09 RajuPedda

@matschik @pablo-abc Would you mind to review the changes please?

RajuPedda avatar Sep 25 '24 17:09 RajuPedda

In Svelte 5 destructuring this is not possible since it would lose reactivity. The value of the property is computed on destructure rather than on access.

pablo-abc avatar Sep 26 '24 07:09 pablo-abc

Yeah, I just test the code on Svelte 5 preview and your right, it loses the reactive nature if you destructuring the state object. Hence closing the PR.

RajuPedda avatar Sep 26 '24 18:09 RajuPedda

Used the $derived state to get the reactive values and it's working now. Would you mind to review the changes please? @pablo-abc Using $derived state

RajuPedda avatar Sep 26 '24 19:09 RajuPedda

I haven't dug that much into how runes work but I'm quite surprised that works :p seems to be expected behaviour, though?

I see some pitfalls mentioned with doing it this way, though. There's two solutions at the end of that issue that seem slightly better?

E.g. without modifying useFetchUsers

const response = useFetchUsers();
const { isLoading, errors, users } = $derived(response);

Although I see no harm in this specific scenario... may be ok already. I'm not sure what you think, @matschik. Final decision is yours in the end 😄


On an unrelated note, I know it has nothing to do with your PR but I don't see why the example is using a class UserResponse to handle the state when something like this could do:

export default function useFetchUsers() {
  let users = $state();
  let error = $state();
  let isLoading = $state(false);

  async function fetchData() {
    isLoading = true;
    try {
      const response = await fetch("https://randomuser.me/api/?results=3");
      users = (await response.json()).results;
      error = undefined;
    } catch (err) {
      error = err;
      users = undefined;
    }
    isLoading = false;
  }
  fetchData();

  return {
    get users() { return users },
    get error() { return error },
    get isLoading() { return isLoading },
  };
}

pablo-abc avatar Sep 26 '24 21:09 pablo-abc