FormidableLabs/react-ssr-prepass

Usage with react-redux

omarahm opened this issue · 1 comments

I am wondering how can I use this library in my already existing codebase. I use react, redux and react-redux to save my components state. Because of how the HoC connect() works by mapping the store state into props and injecting it into the user component, I need to re-render the parent Connect()ed component after the thrown promise is fulfilled, instead of simply re-rendering the current component instance. Can you please help me figure out how to achieve this?

Here's an example:

const MyComponent = (props) => {
  if (!props.postsFetched) {
    throw new fetchPostsFromApi.then(posts => props.savePostsToRedux(posts));
  }
  
  return posts.map(post => <h1>{post.title</h1>);
}

export default connect(
  state => ({
    postsFetched: !!state.posts,
    posts: state.posts || [],
  }),
  dispatch => ({
    savePostsToRedux: posts => dispatch({ type: 'SAVE_POSTS', payload: { posts }});
  }),
)(MyComponent);

Here's a code trace:

  1. react-ssr-prepass first renders MyComponent, catches the promise and await for it
  2. After data is fetched from the API, a Redux action is dispatched and data is saved into the store
  3. react-ssr-prepass attempts to re-render the same instance, meaning the props never get updated from the store (parent not re-called) and thus returning empty list

Any advice on how to tackle that? I am considering forking the code and queue-ing an update for the parent (or maybe the nearest <Suspense /> ancestor in the tree)

Needless to say, great job with this project and thanks in advance for your help.

Hiya, this is more of a question for forums or StackOverflow, or even react-redux itself, as you're looking at implementing a wholly suspended redux fetching API.

I need to re-render the parent Connect()ed component after the thrown promise is fulfilled

This is simply not possible in react-ssr-prepass' approach. It is still in essence a server-side renderer, and it doesn't restart rendering from your last Suspense element up the tree, since those are mostly used for UI changes and not logic right now, in terms of how suspense is being used.

Essentially you can work around this though by not using connect and accessing the Redux context in the same component that is suspending. This is now even easier with the new version of react-redux and/or hooks.