Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte .set is not a function

I am trying to create a todo app with stores in svelte. But I am having an error that I wasn’t able to solve.

I have tried to use stores to manage all my all tasks data even it in not required but I wanted to see how stores work in svelte but I had an error that I don’t really know why.

//App.svelte

<script>
  import { onMount } from "svelte";
  import { tasks } from "./stores";
  import Item from "./assets/Item.svelte";

  var itemText = "";

  function addHandler() {
    var item = {
      value: itemText,
      id: Math.random(),
    };

    itemText = "";
    tasks.add(item);
    tasks.save();
  }

  onMount(() => {
    tasks.load();
  });
</script>

{#each $tasks as task (task.id)}
  <Item bind:value={task.value} />
{/each}

<input type="text" bind:value={itemText} />
<button on:click={addHandler}>Add Item</button>


//Item.svelte

<script>
    import { tasks } from "../stores.js";
    export let value = null;

  $: {
    if (value != null) {
      tasks.save();
      console.log($tasks);
    }
  }
</script>

<div>
  <input bind:value />
</div>

//stores.js
import { writable } from "svelte/store";

function list() {
  const { subscribe, set, update } = writable([]);

  return {
    subscribe,
    save: () => {
      update((items) => {
        localStorage.setItem("items", JSON.stringify(items));
        return items;
      });
    },
    add: (item) => update((items) => [...items, item]),
    remove: (item) => update((items) => items.filter((i) => i !== item)),
    load: () => {
      const items = JSON.parse(localStorage.getItem("items"));
      if (items) set(items);
    },
    update,
  };
}

Error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export var tasks = list();

error: App.svelte:25 Uncaught TypeError: tasks.set is not a function
    at Array.item_value_binding (App.svelte:25:31)
    at Object.item_value_binding (App.svelte:4:42)
    at index.mjs:2020:31
    at HTMLInputElement.input_input_handler (Item.svelte:3:26)

Here is my code I don’t really know what is causing this problem if you can help I would be thankful

>Solution :

You need to return the set function from list() since you’re binding to one of the values in the store:

<Item bind:value={task.value} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading