query graphql to pull listtodo in react in javascript

Assuming you already have a GraphQL endpoint set up and a React application with apollo-client installed, you can query for a list of todos using the following code:

import { useQuery, gql } from "@apollo/client";

const GET_TODOS = gql`
  query {
    listTodo {
      id
      title
      completed
    }
  }
`;

function TodoList() {
  const { loading, error, data } = useQuery(GET_TODOS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return (
    <ul>
      {data.listTodo.map((todo) => (
        <li key={todo.id}>
          {todo.title} - {todo.completed ? "Done" : "Not done"}
        </li>
      ))}
    </ul>
  );
}
495 chars
29 lines

This code defines a GraphQL query GET_TODOS that asks for the id, title, and completed fields of all the todos in the listTodo query. The useQuery hook is used to fetch data from the server, and the returned data and status (loading and error) are used to render a list of todos in the UI.

gistlibby LogSnag