Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invariant Violation: Could not find "store" in either the context or props of "Connect(KnowStatus)". Either wrap the root component in a <Provider>

I am new to Redux When i am server side rendering with redux It throwed me this error

Invariant Violation: Could not find "store" in either the context or props of "Connect(KnowStatus)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(KnowStatus)".

When i am not using serversiderendering it works fine But when I am using it Throws a error like this ...

ServersiderenderExpress.js

import express from 'express';

import bodyParser from 'body-parser';

import {Server} from 'http';
import React from 'react';
import {renderToString} from 'react-dom/server';
import {match, RouterContext} from 'react-router';
import routes from '../client/routes';

import Helmet from 'react-helmet';
import compression from 'compression';
import favicon from 'serve-favicon';


let app = express();
app.use(bodyParser.json());
app.use(compression());
app.use(favicon(__dirname + '/favicon/favicon.ico'))
app.use(express.static('public'));


app.get('*', (req, res) => {
    match({routes, location: req.url}, (err, redirectLocation, renderProps)=> {
        if (err) {
            return res.status(500).send(err.message);
        }
        if (redirectLocation) {
            return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
        }
        let markup;
        let rendered = renderToString(<RouterContext {...renderProps}/>);
        let head = Helmet.rewind();
        if (renderProps) {
            markup = `
            <!DOCTYPE html>
            <html>
              <head>
                <meta charset="utf-8"/>
                ${head.title}
                ${head.meta}
                ${head.link}
              </head>
              <body>
                <div id="app">
                ${rendered}
                </div>
                <script src="bundle.js"></script/>
              </body>
            </html>`
        }
        res.write(markup);
        res.end();


    })
});


app.listen(3000, () => {
    console.log('Listening')
});
like image 770
Nane Avatar asked Dec 07 '16 15:12

Nane


1 Answers

The renderProps returned by the match function only contains information on the route component(s) that should be rendered by on req.url. You still have to render a <Provider> and provide it with a store object.

import { createStore } from 'redux'
import { Provider } from 'react-redux'

match(..., (...) => {

  // ...

  // create the store like you do on the client side, giving
  // it your reducer(s) and possibly an initial state
  const store = createStore(reducer, initialState)
  const rendered = renderToString(
    <Provider store={store}>
      <RouterContext {...renderProps} />
    </Provider>
  )

  // ...

})
like image 88
Paul S Avatar answered Nov 04 '22 02:11

Paul S