What causes the "ctx[1] is not a function" error in this small Svelte app?

Viewed 652

I am working on a small to-do app with Svelte. I list 10 todos from jsonplaceholder.

I have this in App.svelte:

<script>
    import { onMount } from "svelte";
    import Header from './Header.svelte';
    import ToDoList from './ToDoList.svelte';
    import Footer from './Footer.svelte';
    const apiURL = "https://jsonplaceholder.typicode.com/todos";
    const limit = 10;
    let todos = [];
    export let unsolvedTodos = [];
    
    onMount(() => {
        getTodos();
    });
    
    const getTodos = () => {
        fetch(`${apiURL}?&_limit=${limit}`)
        .then(res => res.json())
        .then((data) => todos = data)
        .then(getUnsolvedTodos);
    }
    
    const getUnsolvedTodos = () => {
        unsolvedTodos = todos.filter(todo => {
            return todo.completed === false;
        })
    }

    const deleteTodo = (todo) => {
        let itemIdx = todos.findIndex(x => x == todo);
        todos.splice(itemIdx, 1);
        todos = todos;
  }
</script>

<div class="app-wrapper">
  <div id="toDoApp">
        <Header />
    <ToDoList todos={todos} />
    <Footer />
  </div>
</div>

In ToDoList.app:

<script>
    import TodoItem from './TodoItem.svelte';
    export let todos;
    let deleteTodo;
</script>

{#if todos.length > 0}
  <ul class="todo-list">
    {#each todos as todo, index}
        <TodoItem {todo} on:deleteTodo = {deleteTodo(todo)} />
    {/each}
  </ul>
{/if}

In TodoItem.svelte:

<script>
    import {createEventDispatcher} from 'svelte';
    import { fade, fly } from 'svelte/transition';
    import { flip } from 'svelte/animate';
    export let todo;
    
    const dispatch = createEventDispatcher();
    const Delete = () => dispatch("deleteTodo", todo);
</script>

<li transition:fly="{{x:-100, duration:200}}">
    <input type="checkbox" checked="{todo.completed}" />
    <span class="title {todo.completed ? 'done' : ''}">{todo.title}</span>
    <button on:click="{Delete}"><i class="fa fa-trash" aria-hidden="true"></i></button>
</li>

I must be missing something because I get the error ctx[1] is not a function as can be seen in this REPL.

What am I doing wrong?

1 Answers

In ToDoList.svelte you are calling deleteTodo(todo) but deleteTodo is undefined. Svelte should really throw a better error message here...

Edit:

Also, if you assign an event handler, you want to pass in a reference to a function like on:deleteTodo = {() => deleteTodo(todo)} or on:deleteTodo = {deleteTodo} and not call the function directly.

Related