簡體   English   中英

使用來自 API 的數據初始化 Next.js webapp 並將其添加到 state 的最佳實踐是什么?

[英]What are the best practices to initialize a Next.js webapp with data from an API and adding it to the state?

我正在使用 Zusand 進行 state 管理(盡管我想同樣的原則適用於所有 state 管理庫,例如 Redux 或 Recoil)。 我想過並嘗試過:

  1. 在第一頁渲染期間使用getStaticProps()獲取數據並使用useEffect()將數據推送到 state。 問題是在加載特定頁面之前,數據不會推送到 state。 我不想使用getInitialProps() ,因為它已被棄用。
  2. 一個有效的解決方案(雖然不確定它是否是最佳實踐)是在應用程序首次初始化時在_app.js上使用 SWR 來獲取 API 數據,並使用useEffect()將數據推送到 state 。 這樣,我可以使用 state 中的數據自由填充頁面,並且只需要一次 API 調用。 下面的例子:
function MyApp({ Component, pageProps }) {
  
  // Load data from api with SWR
  const fetcher = (url) => fetch(url).then((res) => res.json());
  const { data, error } = useSWR(
    "https://example.com/api",
    fetcher
  );

  // Get data setter from state
  const setData = useStore((state) => state.setData);

  // When data is fetched successfully, populate state with data
  useEffect(() => {
    if (data) {
      setData(data);
    }
  }, [data]);

  if (error) return "Error has occured";
  if (!data) return "Loading...";

  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

export default MyApp;

有沒有更好的方法來獲取數據並在第一次加載應用程序時使用它來填充 state? 最佳實踐是什么?

我使用 Zusstand 上下文提供程序以正確的方式工作,並使用 Nextjs pagePropsgetStaticProps()對其進行初始化。

_app.js

function MyApp({ Component, pageProps }) {
  const createStore = initStore(pageProps.initZustand);
  return (
    <Provider createStore={createStore}>
      <Component {...pageProps} />
    </Provider>
  );
}

export default MyApp;

store.js

export const { Provider, useStore } = createContext();

let store = {
  names: ["Name 1", "Name 2", "Name 3"],
  random: [],
  setRandom: (data) => {
    set((state) => ({ random: data }));
  },
};

export const initStore = (data) => {
  const createStore = () =>
    create(
      devtools((set, get) => ({
        ...store,
        ...data,
      }))
    );

  return createStore;
};

index.js 獲取靜態屬性:

export async function getStaticProps(context) {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  const posts = await res.json();

  return {
    props: {
      initZustand: {
        posts: posts,
      },
    },
  };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM