Julian White
Julian White

Reputation: 11

React Nextjs routing passing Redux Store

I have a react app that uses a redux store to hold data from a database. The home page has access to this data with the redux store. Other pages cannot access this data. I realize that I need to use a Provider component and have tried that, however I think there is something wrong with the structure as I am using nextjs for routing, and the code on the index page is not getting included.

  //index.js
  
  render() {
    return (
        <Provider store={store}>
            <p>My Page Data</p>
        </Provider>
    );
  }

All examples I see use an component but the template I am using does not use that and exports html directly from the index page instead. How do I have the index.js page as the top level component (holding the provider) and then have all pages as a child of this (so they can access the store). I am using React 16.3.1

Upvotes: 1

Views: 2475

Answers (1)

Denys Kotsur
Denys Kotsur

Reputation: 2599

You should use HoC which wraps your pages with Provider.

If request comes from the server - new store is created and kept in a global variable on the client side. Every time when you are using client routing (for instance, 'next/link') it will grab this store from global variable and pass to the Provider component of another page.

It's already written and commented by Next.js team in this example.

So, your typical page should looks like:

import withRedux from './utils/withRedux'

const SomePage = props => {
    return (
         <SomeLayout>
             <SomeContainer />
         </SomeLayout>
    )
}

export default withRedux()(SomePage)

Upvotes: 2

Related Questions