0

I am using a serverless frame work and tRPC for routes. When I make a call to the backend it will initially be undefined and then return the appropriate data. I am not sure if my call is wrong on the frontend or if there is an issue with retrieving data from the backend. I have tried adding awaits, but nothing worked.

route call

const t = initTRPC.create();

const appRouter = t.router({
  Todos: t.procedure
  .query(() => {
    // console.log(Todo.list())
    return Todo.list()
  })
    })

db query

 export function list() {
    return PG.DB.selectFrom("todo")
    .selectAll()
    .orderBy("todoID")
    .execute()
}

frontend

function IndexPage() {
  const todoList = trpc.Todos.useQuery()?.data;
  console.log("--------", todoList)
  if (!todoList) return <div>Loading...</div>;
  return (
    <div>
     <table className="table table-bordered">
              <thead>
                <tr>
                  <th className="th-sm">task</th>
                </tr>
              </thead>
              <tbody>
                {todoList.map((todo) => {
                  return (
                    <>
                      <tr key={todo?.todoID}>
                        <td>{todo.task}</td>
                      </tr>
                    </>
                  );
                })}
              </tbody>
            </table>
    </div>
  );
}
Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
BillyG
  • 21
  • 2

1 Answers1

2

It's normal for the data to initially be undefined. The query doesn't exist before the component first renders, so the component can't have the data yet (unless it's already in cache for some reason such as also being queried in another component).

If you want to create a component that has the data from a tRPC query as soon as it mounts the first time, you have several options, for example:

  • using server side rendering if your app allows this
  • creating a separate component that displays the data, and only rendering it if data exists

tRPC's useQuery uses Tanstack Query. You can see all of the things you can destructure from the query here: https://tanstack.com/query/v4/docs/react/reference/useQuery