简体   繁体   English

使用 Next.js 对服务器端渲染进行 React Query

[英]React Query with server side rendering using Next.js

I am trying to use react-query with nextjs to prefetch query on server.我正在尝试使用 react-query 和 nextjs 在服务器上预取查询。 It works for the initial query which gets a list of items.它适用于获取项目列表的初始查询。 However when I try to fetch each item inside component it only fetches it on the client side.但是,当我尝试获取组件内的每个项目时,它只会在客户端获取它。

export default function Home() {
  const { data } = useQuery("pokemons", fetchPokemons);
  return (
    <>
      <div>
        {data.map((pokemon) => (
          <Pokemon key={pokemon.name} pokemon={pokemon}/>
        ))}
      </div>
    </>
  );
}

export async function getStaticProps() {
  const queryClient = new QueryClient()
  await queryClient.prefetchQuery('pokemons', fetchPokemons)
  const fetchedPokemons = queryClient.getQueryData()
  //query each pokemon
  fetchedPokemons.forEach(async (pokemon) => {
    await queryClient.prefetchQuery(pokemon.name, () => fetchPokemon(pokemon.url))
  });

  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  }
}

And here is code for the component which also queries each item.这是也查询每个项目的组件的代码。

const Pokemon = ({pokemon}) => {
  
  const {data} = useQuery(pokemon.name, () => fetchPokemon(pokemon.url))
  // logs only in browser, on server it is undefined
  {console.log(data)}
  return (
    <div>
      <h3>
        Name - {data.name}
        </h3>
        <h4>Base XP - {data.base_experience}</h4>
    </div>
  )
}

Can you please tell me what am I doing wrong that the query doesn't execute on server or is it an issue of the library itself?你能告诉我查询没有在服务器上执行还是库本身的问题我做错了什么?

when you use getQueryData to get data from the cache, you need to provide the key of the data you want to get:使用getQueryData从缓存中获取数据时,需要提供要获取的数据的key

await queryClient.prefetchQuery('pokemons', fetchPokemons)
const fetchedPokemons = queryClient.getQueryData('pokemons')

alternatively, you can use fetchQuery to also retrieve the data immediately或者,您也可以使用fetchQuery立即检索数据

try {
  const fetchedPokemons = await queryClient.fetchQuery('pokemons')
} catch (error) {
  // handle error
}

Be aware that fetchQuery throws errors (as opposed to prefetchQuery , which does not), so you might want to handle errors somehow.请注意fetchQuery会引发错误(而不是prefetchQuery ,后者不会),因此您可能希望以某种方式处理错误。

I was able to solve this by combining two of my fetching functions into one like so我可以通过将我的两个获取功能组合成一个来解决这个问题

const fetchPokemons = async () => {
  const { data } = await axios.get(
    "https://pokeapi.co/api/v2/pokemon?limit=10&offset=0"
  );

  const pokemonArray = await Promise.all(
    data.results.map(async (pokemon) => {
      const res = await axios.get(pokemon.url);
      return res.data;
    })
  );

  return pokemonArray;
};

export default function Home() {
  const { data } = useQuery("pokemons", fetchPokemons);
  return (
    <>
      <div>
        {data.map((pokemon) => (
          <Pokemon key={pokemon.name} pokemon={pokemon}/>
        ))}
      </div>
    </>
  );
}

export async function getStaticProps() {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery("pokemons", fetchPokemons);

  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 react-html5video是否与服务器端渲染兼容? (使用next.js) - Is react-html5video is compatible with server side rendering ?? (Using next.js) Next.js 未在服务器端渲染中渲染 CSS - Next.js is not rendering CSS in Server Side Rendering 如何使用React可加载和获取组件数据(如Next.js)进行服务器端渲染? - How to do Server Side Rendering in React With React Loadable and Fetching Data for Components (Like Next.js)? Next.js static 服务器端渲染和 Gatsby.js - Next.js static server side rendering and Gatsby.js 在 Next.js 和/或其他形式的 React 服务器端渲染中延迟加载图像 - Lazy Loading Images in Next.js and/or in other forms of React server-side rendering 使用 next.js 与传统 SSR 进行服务器端渲染 - Server side rendering with next.js vs traditional SSR 如何让 Next.js 做 SSR(服务器端渲染)? - How to make Next.js do SSR (Server Side Rendering)? 用于服务器端渲染的 Next.js 路由器中的匹配和参数对象 - Match and Param object in Next.js router for Server side rendering Next.js:如何将仅外部客户端的 React 组件动态导入到开发的服务器端渲染应用程序中? - Next.js: How to dynamically import external client-side only React components into Server-Side-Rendering apps developed? 服务器端在 React 中使用 Next.js 加载全局组件 - Server side load a global component with Next.js in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM