Uncaught error expected the reducer to be a function

b’

b’

const rootReducer = combineReducers({n    products,n    specialPostsn});nnconst store = createStore( rootReducer, applyMiddleware( thunkMiddleware ));n

n

The initial state is then created automatically from the initial states returned by the individual reducer functions. These individual states can be accessed as state.products and state.specialPosts

The problem was due to rootReducer being imported by require (ES5):

n

var rootReducer = require(./reducers.js);n

n

If you import it via the ES6 method, it will correctly save the rootReducer.js default automatically into rootReducer as you expected:

n

import rootReducer from ./reducers;n

n

I see you are mixing ES5 (require) and ES6 (import) in that file…I was mixing in my project as well, which is why I ran into this problem. More information can be found here: https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0#.2x2p2dx3m

javascript – React+Redux – Uncaught Error: Expected the reducer to be a function

When you create store first argument must be function that means reduce(()=>[]) parameter

n

Error:

n

import {createStore,applyMiddleware} from redux;nnnexport default function configureStore(initialState) {n  return createStore(n    [],n    {},n    applyMiddleware()n  );n}n

n

Solution:

n

import {createStore,applyMiddleware} from redux;nnnexport default function configureStore(initialState) {n  return createStore(n    ()=>[],n    {},n    applyMiddleware()n  );n}n

Related posts on java script  :

  • javascript – Alternative to msSaveOrOpenBlob on Chrome
  • javascript – Whats the source of Error: getaddrinfo EAI_AGAIN?
  • javascript – Npm install cannot find module semver
  • javascript – How to resolve the C:fakepath?
  • javascript – How to reload/refresh jQuery dataTable?
  • javascript – Adding an onclick event to google.map marker
  • javascript – How to use preload.js properly in Electron
  • javascript – How to run html file on localhost?
  • javascript – React store.getState is not a function

@RomansWorks

When running with npm run dev and loading the first page, I got:

[1] Error: Expected the reducer to be a function.
[1]     at createStore (/somedir/node_modules/redux/lib/createStore.js:63:11)
[1]     at /somedir/node_modules/redux/lib/applyMiddleware.js:37:19
[1]     at createStore (create.js:25:17)
[1]     at server.js:71:17
[1]     at Layer.handle [as handle_request] (/somedir/node_modules/express/lib/router/layer.js:95:5)
[1]     at trim_prefix (/somedir/node_modules/express/lib/router/index.js:312:13)
[1]     at /somedir/node_modules/express/lib/router/index.js:280:7
[1]     at Function.process_params (/somedir/node_modules/express/lib/router/index.js:330:12)
[1]     at next (/somedir/node_modules/express/lib/router/index.js:271:10)
[1]     at SendStream.error (/somedir/node_modules/serve-static/index.js:120:7)

This seems to be due to CommonJS require method in src/redux/create.js returning an object instead of the ES6 import’s function:

const reducer = import reducer from './modules/reducer';

Instead, this fixed it for me:

import reducer from './modules/reducer'; 

Are there any unwanted side effects with this change? Should I issues a pull request?

Thanks

@ALIRAZA705

sir i am getting the same error can you pls help me how to fix this … this is my index.js file
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import ‘./index.css’;
import App from ‘./App’;
import * as serviceWorker from ‘./serviceWorker’;
import {createstore, createStore} from ‘redux’
import allreducer from ‘../src/reducer/Counter’
import { composeWithDevTools } from ‘redux-devtools-extension’;
let store = createStore(allreducer,composeWithDevTools)
ReactDOM.render(
<React.StrictMode>

</React.StrictMode>,
document.getElementById(‘root’)
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

and this is my Counter.js file
const counter = (state=0,action) => {
switch(action.type){
case «Increment»:
return state + 1;
case «DeIncrement»:
return state — 1;
default:
return state;
}
}
export default counter
can you pls help me

Every time a web page does more than just sit there and display static information for you to look at, such as providing timely content updates, interactive maps, dynamic 2D/3D visuals, scrolling video jukeboxes, and so on, you can know that JavaScript is involved. It’s the third layer of the standard web technologies layer cake. A high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language, JavaScript is sometimes shortened as JS. One of the three fundamental technologies for creating content for the World Wide Web, together with HTML and CSS, is JavaScript. It is employed to give online applications, such as video games, and to make web pages interactive. The majority of websites use it, and because of a built-in JavaScript engine, all current web browsers support it without the need for plug-ins.

JavaScript is a programming or scripting language for creating dynamically updated material, controlling multimedia, animating pictures, and pretty much anything else. Okay, not everything, but it’s incredible what a few pieces of JavaScript code can accomplish.

Photo by nandhukumar

Table of Contents:

                1 — What is the uncaught error: expected the reducer to be a function 
                2 — Why this message will be thrown 
                3 — The Solution  
                               1 — The Solution One 

                               2 — The Solution Two 
                4 — The Conclusion

What is the uncaught error: expected the reducer to be a function.

The error thrown is Uncaught Error: Expected the reducer to be a function in javascript.

To understand why this error is thrown, you need to know that redux uses Redux-Thunk middleware to allow async flow control in the application. This middleware allows functions to return another function instead of the actual data from the server. The problem is that since these functions return another function, they can’t be used as reducers for Redux and this creates an Uncaught TypeError: Expected String but got Function exception because there are no string values returned by a thunked action (or indeed any other type).

Why this message will be thrown

I was trying to use Redux, but I kept getting an error: «Uncaught Error: Expected the reducer to be a function.» This is probably because you’ve imported a named function instead of an anonymous function. In your import statement. The «Uncaught error: Expected the reducer to be a function» error happens frequently. It usually happens when you import a named function or class instead of using an anonymous function.

A function without a name is said to be anonymous. Why would you want to employ such a thing? Well, let’s say you’re writing JavaScript in an environment where the only thing available to you is console.log (and maybe a few other methods). These functions are called immediately as they’re defined and thus don’t need a name since it’s not necessary for them to do anything useful after they’ve been called once.

You can import a function from another file by using the import keyword and providing it with the path. The path can be relative or absolute, which means that you could use ./myReducer or /path/to/myReducer as the path to your reducer. Importing a function allows you to use it in another file, even if that other file doesn’t have access to its original scope

Other times, using an anonymous function can help keep code organized and make it shorter, which is always good!

The Solution

I am writing here two examples of the solution.

The Solution One

To fix this error, you need to change your import statement to use an anonymous function instead of a named one:

import * as Redux from 'redux'; // Old code
const myNamedReducer = (state) => { // ... } // New Code const myAnonymousReducer = (state) => { // ... }

In your import statement, try changing this:

import myReducer from './reducer'; //for example this is your current code then change it to as
import { myReducer } from './reducer'; //change it like this
import { myReducer } from './reducer'; //if your code is currently like this
import myReducer from './reducer'; // then change it like this

In this case, the problem is that you are trying to import a named function that was exported from another file. This is the correct syntax:

import myReducer from './reducer';

The reason for the warning is that in JavaScript, you can only specify the exact name of a module (in this case “myReducer”) when you export it. If there were no such exported name, then we would get an error like “TypeError: expected string or number as the first argument but got object” since it cannot be determined which module we mean by just typing out its pathname.

In order to solve the issue. You will need to: 

  • Remove the file extension from the path.
  • Change it to a .js file.

The Solution two

const rootReducer = combineReducers({n    products,n    specialPostsn});nnconst store = createStore( rootReducer, applyMiddleware( thunkMiddleware ));n

From the initial states that each reducer function has returned, the initial state is then automatically generated. State.products and state can be used to access these particular states.specialPosts

rootReducer was imported by require (ES5), which caused the issue:

var rootReducer = require(./reducers.js);n

It will successfully store the rootReducer.js default automatically into rootReducer as you anticipated if you import it using the ES6 method:

import rootReducer from ./reducers;n

In the above case combining ES5 (need) and ES6 (import) in that file, I did the same thing in my project, which is why I had this issue. So the right code would be:

import {createStore,applyMiddleware} from redux;nnnexport default function configureStore(initialState) {n  return createStore(n ()=>[],n {},n  applyMiddleware()n  );n}n

The Conclusion

Even a little syntactic error in the code might lead to issues. If you are new to the world of coding, don’t panic; we are here to help you and provide fixes for these issues.

We encourage your input. If you’d like to leave a comment, please do so in the comments section or the feedback section.

So, you’re all set. You have a better understanding of how to fix this error and can go back to using Redux without worrying about it.

Я получил сообщение об ошибке, но я не уверен, как его решить:

Uncaught Error: Expected the reducer to be a function

Вот несколько частей моего рабочего процесса реакции/сокращения:

корневой редуктор

import { combineReducers } from 'redux';
import PostsReducer from './reducer_posts';
import StreakReducer from './reducer_streak';
import { reducer as formReducer } from 'redux-form';

const rootReducer = combineReducers({
  entries: PostsReducer,
  form: formReducer,
  streak: StreakReducer
});

export default rootReducer;

создатель действия

import axios from 'axios';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers/index';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

export const FETCH_ENTRIES = 'FETCH_ENTRIES';
export const FETCH_LONGEST = 'FETCH_LONGEST';

const ROOT_URL = 'http://localhost:3000/entries';

export function fetchEntries() {
  const request = axios.get('${ROOT_URL}');
  return {
    type: FETCH_ENTRIES,
    payload: request
  };
}


// action creator for returning the longest streak of rejections
export function longestStreak() {
  return function(dispatch) {
    return fetchEntries().then(
      entries => dispatch(findLongestStreak(entries))
    );
  };
}


function findLongestStreak(entries) {
  var longestStreakLength = 10;
  return {
    type: FETCH_LONGEST,
    payload: longestStreakLength
  };
}

редуктор штрихов

import { FETCH_LONGEST } from '../actions/index';

const INITIAL_STATE = { streak: 0 };

export default function(state = INITIAL_STATE, action) {
  switch(action.type) {
    case FETCH_LONGEST:
      return { ...state, streakInfo: action.payload.data};
    default:
      return state;
  }
}

Сообщений Редуктор

import { FETCH_ENTRIES, CREATE_ENTRY } from '../actions/index';

const INITIAL_STATE = { all: [], entry: null };

export default function(state = INITIAL_STATE, action) {
  switch(action.type) {
    case CREATE_ENTRY:
      return {...state, entry: action.payload.data };
    case FETCH_ENTRIES:
      return { ...state, all: action.payload.data };
    default:
      return state;
  }
}

Компонент

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { longestStreak } from '../actions/index';


class EntriesMetadata extends Component {
  componentWillMount() {
    this.props.longestStreak();
  }

  render() {
    return (
        <div>
      </div>
    );
    }
  }

function mapStateToProps(state) {
  return { streak: state.streak.streakInfo };
}

export default connect(mapStateToProps, { longestStreak })(EntriesMetadata);

Я не понимаю, как решить эту проблему. Может кто-то указать мне верное направление? Это мой самый первый проект сокращения! Пожалуйста, дайте мне знать, нужны ли какие-либо дополнительные фрагменты.

РЕДАКТИРОВАТЬ

Вот мой github repo: https://github.com/pchung39/courage

Понравилась статья? Поделить с друзьями:
  • Uncaught error dropzone already attached
  • Uncaught error class evtimer not found
  • Uncaught error call to undefined function imagecreatefrompng
  • Uncaught error call to undefined function gregwar captcha imagecreatetruecolor
  • Uncaught error call to undefined function curl init