Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to perform reactive based on prop change #225

Open
sysmat opened this issue Nov 1, 2024 · 1 comment
Open

how to perform reactive based on prop change #225

sysmat opened this issue Nov 1, 2024 · 1 comment

Comments

@sysmat
Copy link

sysmat commented Nov 1, 2024

  • is there better way to perform tack reactive?
  • I'm doing this
let { id }: IDProp = $props();

let orgPromise = $derived(getOrg(id));

const getOrgTask = task(async (param: number) => {
	wait timeout(200);
        return await getOrg(id);		
});

let orgTask = $derived(getOrgTask.perform(id));
  • if I jus do getOrgTask.perform(id), then when id change I always get the same org
@paoloricciuti
Copy link
Collaborator

  • is there better way to perform tack reactive?
  • I'm doing this
let { id }: IDProp = $props();

let orgPromise = $derived(getOrg(id));

const getOrgTask = task(async (param: number) => {
	wait timeout(200);
        return await getOrg(id);		
});

let orgTask = $derived(getOrgTask.perform(id));
  • if I jus do getOrgTask.perform(id), then when id change I always get the same org

Hi...the return value of the task function it's already a store and kinda reactive by itself. The return value of the perform function is the task instance but you likely want to access the result from the orgTask store itself. If you want to instantiate a new task everytime the prop change you likely want to have the whole task function in the derived like this

<script>
    let { id }: IDProp = $props();

    let orgTask = $derived.by(()=>{
        // you want to have an explicit dependency on id since it will not be picked up
        // by the reactivity system within the async function inside task.
        id;
        return task(async (param: number) => {
            wait timeout(200);
            return await getOrg(id);		
        });
    });
</script>

and then use it normally through the application

$orgTask.lastSuccessful.value;

Here's a repl that shows this behaviour: https://svelte.dev/playground/5543f206b1924fd69a3ba38df6b20066?version=5.1.12

Keep in mind that you are creating a new task everytime id changes so i don't know if that's exactly what you need. If you have an example of what you want to achieve i can probably help you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants