0
votes

I've been working on next.js project using redux-saga. I wanted to fetch data before every page load so I use getInitialProps in next.js. My desire behavior of application was

  1. Go to localhost:3000

  2. redirect to login page

  3. fetch user data in getInitialProps to SSR in Profile component

However, before all data successfully fetched, application load main page with blank profile component. After refreshing page, I can see the data in Profile component.

Here's my _app.js

MyApp.getInitialProps = async (context) => {
  const keycloak = Keycloak(context.ctx.req);

  const token = keycloak.token

  const { ctx, Component } = context;
  let pageProps = {};
  //const state = ctx.store.getState();
  if (tokenStr && tokenStr.length > 0) {
      ctx.store.dispatch({
          type : LOAD_USER_REQUEST,
          data: token
      })

  }
  ctx.store.dispatch(END);
  await ctx.store.sagaTask.toPromise();
  return {
    cookies: parseCookies(context.ctx.req),
    token: keycloak.token,
  };
};

Here's my userReducer.js


const reducer = (state = initialState, action) => produce(state, (draft) => {
  switch (action.type) {
    case LOAD_USER_REQUEST:
      draft.loadUserInfoLoading = true;
      draft.loadUserInfoError = null;
      draft.loadUserInfoDone = false;
      break;
    case LOAD_USER_SUCCESS:
      draft.loadUserInfoLoading = false;
      draft.userInfo.data = action.data;
      draft.loadUserInfoDone = true;
      break;
    case LOAD_USER_ERROR:
      draft.loadUserInfoLoading = false;
      draft.loadUserInfoError = action.error;
      break;

    default:
      break;
  }
});

export default reducer;

How to prevent my application loading page if datas are not fully fetched?

1

1 Answers

0
votes

This would only happen when you are using a localhost, deploy the website and see if the issue still occurs.