Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
What are the best practices to initialize a Next.js webapp with data from an API and adding it to the state?

I'm using Zustand for state management (although I'd imagine the same principle applies to all state management libraries such as Redux or Recoil). I've thought about and tried:

  1. Fetching data using getStaticProps() and using useEffect() to push the data to state during the first page render. The problem is that the data isn't pushed to state until that specific page is loaded. I don't want to use getInitialProps(), as it's being deprecated.
  2. A solution that worked (sort of, not sure it's best practice though) was using SWR on _app.js to fetch the API data when the app first initializes, and pushing the data to state with useEffect(). This way I could freely populate the pages by using the data from state, and it only required one API call. Example below:
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;

Are there better ways to fetch data and use it to populate state on the first time the app is loaded? What are the best practices?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I got it working the right way using Zustand context provider and initializing it using Nextjs pageProps and getStaticProps().

_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 getStaticProps:

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

  return {
    props: {
      initZustand: {
        posts: posts,
      },
    },
  };
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda