Fetch Data Only Once – Remix

huangapple go评论48阅读模式
英文:

Fetch Data Only Once - Remix

问题

我正在使用Remix(1.16)尝试从数据库中获取数据,但只希望获取一次。

我从数据库中获取的数据永远不会更改。这些数据通常是选择输入字段的选项。

我尝试过的方法:

在我的根路由的loader()中获取数据,然后通过useOutletContext()将这些数据传递给项目的其他部分。问题是,每次应用程序上发生POST请求时,根路由上的loader也会刷新并重新获取数据。

在根路由上获取数据

export async function loader({ request }) {
  const staticData = await getStaticData(request)
  return staticData
}

在根路由上将数据传递到上下文中

...
const staticData = useLoaderData()
return (
  <Document>
    <Outlet context={{ staticData }} />
  </Document>
);

如果有人能帮助我解决这个问题,我将不胜感激。

英文:

I'm using Remix(1.16) and trying to fetch data from the database only once.

I have data that I fetch from the database that will never change. These data are usually options of select input fields.

What I tried:

Fetching it on the loader() of my root and passing this data to the rest of the project by the useOutletContext(). The problem is that on every post request that happens on the app the loader on the root is also refreshed and fetch the data again.

Getting the data on root

export async function loader({ request }) {
  const staticData = await getStaticData(request)
  return staticData
}

Passing the data on context on root

  ...
  const staticData = useLoaderData()
  return (
    &lt;Document&gt;
      &lt;Outlet context={{ staticData}} /&gt;
    &lt;/Document&gt;
  );

If someone could help me with that I would greatly appreciate it.

答案1

得分: 1

Add the export shouldRevalidate to your route. If you return false, then Remix will not call your loader again.

https://remix.run/docs/en/main/route/should-revalidate

英文:

Add the export shouldRevalidate to your route. If you return false, then Remix will not call your loader again.

https://remix.run/docs/en/main/route/should-revalidate

huangapple
  • 本文由 发表于 2023年5月17日 07:25:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76267682.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定