typescript React TS返回未定义,然后返回数据

pftdvrlh  于 2023-02-10  发布在  TypeScript
关注(0)|答案(1)|浏览(130)

我正在使用无服务器框架和tRPC进行路由。当我调用后端时,它最初是未定义的,然后返回适当的数据。我不确定我的调用是否在前端出错,或者是否从后端检索数据有问题。我尝试添加等待,但没有任何效果。
路由呼叫

const t = initTRPC.create();

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

数据库查询

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

前端

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>
  );
}
uelo1irk

uelo1irk1#

要获取数据,最好的方法是在安装组件后使用useEffect挂钩

import { useEffect, useState } from "react";

function IndexPage() {
    const [todoList,setTodoList] = useState('')
  
    useEffect(() => {
    const todoList = trpc.Todos.useQuery()?.data; // you should await for data here
    setTodoList(todoList)
    },[])
  
    return (
      <div>
       {todoList === '' ? (<div>Loading...</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>
    );
  }

相关问题