{% include "../header.html" %}
<h1>Your TODOs</h1>
<script>
  const new_task = async (todos, task) => {
    const result = await axios({
      method: "post",
      url: "/todo_alpine",
      data: {task},
      headers: {
        Accept: "application/json"
      }
    });

    // zero error handling but fine for now
    return result.data;
  }

  const list_todo = async () => {
    const result = await axios({
      method: "get",
      url: "/todo_alpine",
      headers: {
        Accept: "application/json"
      }
    });

    return result.data;
  }
</script>

<p>Welcome {{ name }}, here's your TODOs</p>

<div
  x-data="{todos: []}"
  x-init="todos = await list_todo()">
  <ol>
    <template x-for="todo of todos">
      <li x-text="todo.task"></li>
    </template>
  </ol>

  <h4>Add a New TODO</h4>
  <form action="/todo_alpine" @submit.prevent="todos = await new_task(todos, task), task = ''" method="POST" x-data="{task: ''}">
    <label for="task">Task</label>
    <input name="task" x-model="task"></input>
    <button type="button" @click="todos = await new_task(todos, task), task = ''">Submit</button>
  </form>

</div>
{% include "../footer.html" %}