Search code examples
javascriptaws-amplify

How to get the Amplify Data example to work


I'm building an app using React on Amplify and I'm adding a database. I followed the instructions here. List seems to work and returns an empty array. But, create is not working with no error. I'm using NoSQL Workbench and I see the tables but no data. With no error to go on I don't know what to try next.

import { useState, useEffect } from "react";
import { generateClient } from "aws-amplify/data";

const client = generateClient();

const TodoList = () => {
  const [todos, setTodos] = useState([]);

  const fetchTodos = async () => {
    const { data: items, errors } = await client.models.Things.list();
    console.log(items, errors);
    setTodos(items);
  };

  useEffect(() => {
    void fetchTodos();
  }, []);

  const createTodo = async () => {
    try {
      await client.models.Things.create({
        content: window.prompt("Todo content?"),
        isDone: false,
      });

      void fetchTodos();
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <div>
      <button onClick={createTodo}>Add new todo</button>
      <ul>
        {todos.map(({ id, content }) => (
          <li key={id}>{content}</li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;

Solution

  • Turns out the problem was the isDone field was not defined in the resource.ts file. Found this by examining the return value of client.models.Things.create which was return the error message in an "errors" array. The example should be updated with this check. The try catch is prob not a bad idea either.

    const createTodo = async () => {
      try {
        const result = await client.models.Todo.create({
          content: window.prompt("Todo content?")
        });
    
        if (result.errors.length > 0) {
          console.error('Error during create: ', result.errors);
          return;
        }
    
        void fetchTodos();
      } catch (error) {
        console.error(error);
      }
    }