Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while applying applyMiddleware(thunk) getting "Cannot call a class as a function" , in react js

Here is my index.js file code -

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'; 
import { Provider } from 'react-redux';
import thunk from 'react-thunk';
import { createStore, applyMiddleware } from 'redux';
import Login from './Components/LoginRegister';

const store= createStore(
        (state = {}) => state, 
        applyMiddleware(thunk)
    );

ReactDOM.render(( 
    <Provider store={store}>
      <Router>
        <switch>
            <Route exact path="/" component={App} />
            <Route path="/Loginregister" component={Login} />
        </switch>
      </Router>
    </Provider>  ),
  document.getElementById('root')
);

as I am passing 'thunk' in 'applyMiddleware' as 'applyMiddleware(thunk)' then I am getting below error on console -

Uncaught TypeError: Cannot call a class as a function
    at _classCallCheck (index.js:15)
    at ReactThunk (index.js:36)
    at applyMiddleware.js:51
    at createStore (createStore.js:65)
    at Object.<anonymous> (index.js:11)
    at __webpack_require__ (bootstrap b42575b…:555)
    at fn (bootstrap b42575b…:86)
    at Object.<anonymous> (bootstrap b42575b…:578)
    at __webpack_require__ (bootstrap b42575b…:555)
    at bootstrap b42575b…:578

please let me know what I am doing wrong.

like image 993
Atul Avatar asked Nov 28 '22 00:11

Atul


2 Answers

You're importing

import thunk from 'react-thunk';

But thunk is from the redux-thunk module.

So you should import

import thunk from 'redux-thunk';

Moreover I think there will be a problem with your call of "createStore".

createStore takes a reducer (or combined reducers) and possible middleware.

A reducer takes a state and an action and has to return the new state of the store.

function reducer(state, action){

  // Switch-Case for action.type
  // Copy the current state and apply changes

  return state;
}
like image 188
Björn Böing Avatar answered May 23 '23 04:05

Björn Böing


Well, your problem is obvious from the error. You cannot send a function as a class. in createStore() your first argument is a function. It should be the combined reducers you have.

Create a file with the reducers you have, import it to the index file. then do something like

const store = createStore(rootReducer, applyMiddleware(thunk))
like image 31
Mamdouh Alsarayreh Avatar answered May 23 '23 03:05

Mamdouh Alsarayreh