Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property ‘getState’ of undefined

Tags:

reactjs

redux

I want to try small redux example so I installed redux but I got this error

TypeError: Cannot read property ‘getState’ of undefined

new Provider webpack-internal:///./node_modules/react-redux/es/components/Provider.js:24:25

Code:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import './index.css';

const App = () => (<div>Hi </div>);

ReactDOM.render(<Provider><App /></Provider>, document.getElementById('root'));

What is wrong ?

like image 828
zac Avatar asked Feb 24 '19 00:02

zac


3 Answers

If we look inside react-redux <Provider />

<Provider /> expects to be provided a store prop:

this.state = {
  storeState: store.getState(),
                   ^^here
  store
}

Hence the error.

You can create one, though, using a reducer, should be something similar to this:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducer from './reducer'
import App from './components/App'

const store = createStore(reducer)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
like image 57
Karen Grigoryan Avatar answered Sep 21 '22 12:09

Karen Grigoryan


You can add dummy store so you can use your provider.

Provider needs store..

if you not add this u got error... TypeError: Cannot read property ‘getState’ of undefined

so add ..

const store = createStore(() => [], {}, applyMiddleware());

so u can use like this...

<Provider store={store}>
   <App />
</Provider>
like image 20
Daksh Patel Avatar answered Sep 20 '22 12:09

Daksh Patel


You need to add a store to your provider.

If you don't have any reducer, you can add a dummy reducer.

Assume that the dummy reducer returns an empty array.

() => []

So, your code will be changed to:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux'; 

const store = createStore(() => [], {}, applyMiddleware());

import './index.css';

const App = () => (<div>Hi </div>);

ReactDOM.render(<Provider store={store}><App /></Provider>, 
document.getElementById('root'));
like image 29
Mohannad Raslan Avatar answered Sep 20 '22 12:09

Mohannad Raslan