简体   繁体   中英

Accessing redux state when dispatch called in NextJS getInitialProps

I am using Next.js and would like to prefetch an API item using redux. Here's some code that almost works:

class Thing extends Component {
  static getInitialProps ({ store }) {
    store.dispatch(fetchProduct())
  }
}


const mapStateToProps = (state, ownProps) => {
  return {
    product: getProduct()
  }
}

I am running into the issue that the component renders before getProduct has info. How can I shape things so that I don't render until dispatch has fetched the item? I am using redux-api-middleware in case that matters. I can check for the existence/validity of 'product' in render but that sort of defeats the purpose of getInitialProps . Is there a way to achieve the equivalent of an async/await fetch with redux?

Update Ok this might not work. redux-api-middlewar seems to return an empty object as an action on SSR - so its not a timing issue.

Ok. Reading up some GH issues I found that using redux-api-middleware in SSR is somewhat problematic. I believe that part of the issue is that it doesn't appear to return a promise from dispatch that can be used with async/await. Additionally one should ideally use getInitialProps for its intended purpose so let's return the props there directly.

I've switched to redux-axios-middleware and it works like a charm.

static async getInitialProps ({ store }) {
  await store.dispatch(fetchProducts())
  return { products: getProducts(store.getState()) }
}

If you are using 'next-redux-wrapper' you must accept initialState argument in makeStore and pass it down to createStore so that after dispatching the store the new state will be accesible in the server and client side in the object methods.

const makestore = initialState => {
  return createStore(reducer, initialState);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM