react redux applyMiddleware is not a function - javascript

Couldn't spot any flaw in my code myself, I got error of
Uncaught TypeError: (0 , _reactRedux.applyMiddleware) is not a
function
import { applyMiddleware, createStore } from 'react-redux'
import { promiseMiddleware } from './middleware'
const defaultState = {
appName: 'conduit',
}
const reducer = (state = defaultState, action) => {
switch(action.type) {
case 'HOME_PAGE_LOADED':
return { ...state, articles: action.payload.articles }
}
return state
}
const middleware = applyMiddleware(promiseMiddleware)
const store = createStore(reducer, middleware)
export default store
Any clue what's wrong?

You've got your imports mixed up. createStore and applyMiddleware are part of the main Redux package, not React-Redux. You need:
import {createStore, applyMiddleware} from "redux";

You need to call promise middleware like this
const middleware = applyMiddleware(promiseMiddleware())
i.e- Use function brackets after promiseMiddleware text.
See documentation here-

Related

Getting 'import/no-anonymous-default-export' warning for named functions in React

I'm working with a React / Redux app that for some reason is getting a 'import/no-anonymous-default-export' warning for the app reducers even though the reducer functions are named.
userRedirect.js
import {SET_USER_REDIRECT} from "../actions/actionTypes";
const initialState = {
active: false,
title: '',
messages: [],
btnText: ''
};
const userRedirect = (state = initialState, action) => {
switch (action.type) {
case SET_USER_REDIRECT:
let newState = {...state};
newState = {...newState, ...action.payload.redirectData};
return newState;
default:
return state;
}
};
export default userRedirect;
This reducer is being imported into a index.js that is located in a reducers folder where userRedirect.js is also located. It then uses combineReducers method from redux to handle the reducers.
import {combineReducers} from 'redux';
import userData from './userData';
import userRedirect from './userRedirect';
export default combineReducers({
userData,
userRedirect
});
This is then imported into the index of a store folder where this happens:
import {createStore, applyMiddleware} from "redux";
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from "./../reducers";
export default createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
To me it seems like there is a error with the plugin or something, but I've tried npm install, I've tried creating the userRedirect reducer using a function declaration and not a expression, but no matter what I do it keeps showing the warning and for the life of me I cannot figure out why.
Do you guys have any ideas or suggestions in regards to this? Am I just missing something?
Much appreciate it!
[
export default combineReducers({
userData,
userRedirect
});
export default createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
These two are anonymous export.
Change it to
const rootReducer = combineReducers({
userData,
userRedirect
});
export default rootReducer;
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
export default store;
Forgive me if does not look good ... answering from mobile.
Not able to format from mobile

Logout React Reducer w/ History, State & Action Bug

Hey I've looked at a bunch of help files now and cant seem to get the issue solved. Most suggestions are using a different setup than I have. The main issue that the others dont have is the LOGOUT feature. Can you suggest another way to handle the LOGOUT?
Here is my index.js for "combine reducers":
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
import { LOGOUT_USER } from '../constants/index';
/* App Reducer Files */
import app from './app/reducer';
import accountData from './account/reducer';
import employeeData from './employee/reducer';
import locationData from './location/reducer';
import googleData from './google/reducer';
import requestData from './request/reducer';
import menuItemData from './menuItem/reducer';
import orderData from './order/reducer';
/* Public Reducer Files */
import valorData from './valor/reducer';
const appReducer = history => combineReducers({
router: connectRouter(history),
app,
accountData,
employeeData,
locationData,
googleData,
requestData,
menuItemData,
orderData,
// Public
valorData,
});
const rootReducer = history => (state, action) => {
if (action.type === LOGOUT_USER) {
state = undefined;
}
return appReducer(history, state, action);
};
export default rootReducer;
And my store.js:
import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { routerMiddleware } from 'connected-react-router';
import rootReducer from '../services';
import history from '../history';
const debugware = [];
if (process.env.NODE_ENV !== 'production') {
debugware.push(createLogger({
collapsed: true,
}));
}
export default function configureStore(initialState) {
const store = createStore(
rootReducer(history),
initialState,
compose(
applyMiddleware(
routerMiddleware(history),
thunkMiddleware,
...debugware,
),
),
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../services', () => {
const nextRootReducer = require('../services/index').default;
store.replaceReducer(nextRootReducer);
});
}
return store;
}
This was working before I upgraded to a new router version. Again the main issue is the LOGOUT. If I just export appReducer it works just fine but doesnt logout.
WOW. The moment I post it I try one more thing...
const rootReducer = history => (state, action) => {
if (action.type === LOGOUT_USER) {
state = undefined;
}
return appReducer(history)(state, action);
};
Why are you returning an undefined state? Instead, return
if (action.type === LOGOUT_USER) {
return{ ...state, user: [] }
}
It basically returns and empty array as user.

Unexpected key found in preloadedState argument passed to createStore

I am trying to write a redux integration test. My test successfully passes, however, I get the message:
console.error node_modules/redux/lib/utils/warning.js:14
Unexpected key "word" found in preloadedState argument passed to createStore. Expected to find one of the known reducer keys instead:
"jotto", "router". Unexpected keys will be ignored.
It seems to me that my createStore and root reducer look fine. Is there something I need to change that is messing up this preloaded state? You can find the scripts below. Thanks!
jottoRedux.test.js:
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import {routerMiddleware} from 'connected-react-router';
import rootReducer from 'reducers/rootReducer';
import {initialState} from './jottoReducer';
import {createBrowserHistory} from 'history';
export const history = createBrowserHistory();
const middleware = applyMiddleware(routerMiddleware(history), thunkMiddleware);
export const storeFactory = () =>
createStore(rootReducer(createBrowserHistory()), {...initialState}, middleware);
export const setWord = (word) => ({
type: 'SET_WORD',
word,
});
describe('testing SET_WORD action', () => {
let store;
beforeEach(() => {
store = storeFactory();
});
test('state is updated correctly for an unsuccessful guess', () => {
store.dispatch(setWord('foo'));
const expectedState = {
...initialState,
word: 'foo',
};
const newState = store.getState().jotto;
expect(newState).toEqual(expectedState);
});
});
jottoReducer.js:
export const initialState = {
word: null,
};
const jotto = (state = initialState, action) => {
switch (action.type) {
case 'SET_WORD':
return {
...state,
word: action.word,
};
default:
return state;
}
};
export default jotto;
rootReducer:
import {combineReducers} from 'redux';
import {connectRouter} from 'connected-react-router';
import jotto from './jottoReducer';
export default (historyObject) => combineReducers({
jotto,
router: connectRouter(historyObject),
});
Try this:
export const storeFactory = () =>
createStore(rootReducer(createBrowserHistory()), { jotto: initialState }, middleware);

Uncaught TypeError: Providing your root Epic to createEpicMiddleware(rootEpic)

I am getting this error
Uncaught TypeError: Providing your root Epic to
createEpicMiddleware(rootEpic) is no longer supported, instead use
epicMiddleware.run(rootEpic)
When simply using
import 'rxjs'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { reducer as formReducer } from 'redux-form'
import thunk from 'redux-thunk'
import promise from 'redux-promise-middleware'
import { createEpicMiddleware, combineEpics } from 'redux-observable'
import app from './app'
// Bundling Epics
const rootEpic = combineEpics(
)
// Creating Bundled Epic
const epicMiddleware = createEpicMiddleware(rootEpic)
// Define Middleware
const middleware = [
thunk,
promise(),
epicMiddleware
]
// Define Reducers
const reducers = combineReducers({
form: formReducer
})
// Create Store
export default createStore(reducers,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(...middleware))
Kindly help to resolve this
First, take a look at this document: Official Redux-Observable Document because we're using the newest version of Redux-Observable, then reviewing its document is quite helpful.
After reviewing the document, let's see a small example project (Counter app):
This is the root.js file which contains my Epics and Reducers after bundling.
// This is a sample reducers and epics for a Counter app.
import { combineEpics } from 'redux-observable';
import { combineReducers } from 'redux';
import counter, {
setCounterEpic,
incrementEpic,
decrementEpic
} from './reducers/counter';
// bundling Epics
export const rootEpic = combineEpics(
setCounterEpic,
incrementEpic,
decrementEpic
);
// bundling Reducers
export const rootReducer = combineReducers({
counter
});
And this is store.js where I define my store before using it.
import { createStore, applyMiddleware } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { rootEpic, rootReducer } from './root';
import { composeWithDevTools } from 'redux-devtools-extension';
const epicMiddleware = createEpicMiddleware();
const middlewares = [
epicMiddleware
]
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(middlewares))
);
epicMiddleware.run(rootEpic);
export default store;
In order to successfully implement redux-observable, we have to obey this order:
Creating epicMiddleware using createEpicMiddleware() method
Using the applyMiddleware() method to register the epicMiddleware (the redux-devtools-extension is optional)
Calling the epicMiddleware.run() with the rootEpic we created earlier.
This is the instruction from the Redux-Observable Document
For more information, you could find it here: : Setting Up The Middleware:
Try this
import 'rxjs'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { reducer as formReducer } from 'redux-form'
import thunk from 'redux-thunk'
import promise from 'redux-promise-middleware'
import { createEpicMiddleware, combineEpics } from 'redux-observable'
import app from './app'
// Bundling Epics
const rootEpic = combineEpics(
)
// Creating Bundled Epic
const epicMiddleware = createEpicMiddleware();
// Define Middleware
const middleware = [
thunk,
promise(),
epicMiddleware
]
// Define Reducers
const reducers = combineReducers({
form: formReducer
})
// Create Store
const store = createStore(reducers,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(...middleware))
epicMiddleware.run(rootEpic);
export default store
official documentation createEpicMiddleware.
Well, have you tried:
import { epicMiddleware, combineEpics } from 'redux-observable'
const epicMiddleware = epicMiddleware.run(rootEpic)
?

React-Redux - No reducer provided for key "coins"

Not sure why I'm getting the following errors.
I'm just setting up my store, actions and reducers, I haven't called dispatch on anything yet.
Expected
App runs fine, Redux state is not updated
Results
src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
import App from './App'
import css from './coinhover.scss'
const element = document.getElementById('coinhover');
const store = createStore(reducer, compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
));
ReactDOM.render(
<Provider store={ store }>
<App />
</Provider>, element);
src/reducer/index.js
import { combineReducers } from 'redux'
import { coins } from './coins'
export default combineReducers({
coins
});
src/reducer/actions/coins.js
import * as api from '../../services/api'
import { storage, addToPortfolio } from '../../services/coinFactory'
export const ADD_COIN = 'ADD_COIN'
export function getCoin(coin) {
return dispatch => {
api.getCoin(coin)
.then((res_coin) => addToPortfolio(res_coin))
.then((portfolio) => dispatch(updatePortfolio(portfolio)));
}
}
export function updatePortfolio(portfolio) {
return {
type: ADD_COIN,
portfolio
}
}
finally src/reducer/coins/index.js
import { ADD_COIN } from './actions'
const initialState = [];
export default (state = initialState, action) => {
switch(action.type) {
case ADD_COIN:
return action.portfolio;
default:
return state;
}
}
Your issue lies with how you're importing your coins reducer:
import { coins } from './coins'
The latter tries to obtain a named export returned from the file in ./coins.
You are not using any named exports only export default, therefore you just need to import the file as follows:
import coins from './coins';
Using the latter will result with the fact that coins will then contain the value of export default; which will be the coins reducer.
Even when all your imports are correctly imported, this can still happen for one other reason. Circular Dependency!
In my case, this happeded because of a circular dependency in a file. I had two circular dependecy in the project that I created accedentally. Example: rootReducer.ts -> authSlice.ts -> rootReducer.ts.
These dependencies are often not as easy to debug. I used this package to check for circular dependencies. Once the circular dependency was removed, all was well.
Ah just found it, I was importing my coins reducer incorrectly...
import { combineReducers } from 'redux'
import coins from './coins' // because I have coins/index.js
export default combineReducers({
coins
});
instead of
import { coins } from './coins'
This was my fix:
import { combineReducers } from 'redux'
import { coins } from './coins'
export default combineReducers({
coinsState: coins || (() => null) // By adding this I resolved it.
});
If nothing worked for you this might be a circular dependency. I had a project like that requiring store state in the slice. Instead of using the store there was a thunk available that can provide you with the state without importing the store itself. If you have this edge case you can get state from thunk.
thunkAPI.getState()
In my case, I was not adding a default property to my reducers. When I added it, it worked.
here is my code;
const counterReducer = (state = 0, action) => {
switch(action.type){
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
export default counterReducer;
and combinde file;
import counter from './counter';
import { combineReducers } from 'redux';
const allReducers = combineReducers({
counter: counter,
});
export default allReducers;

Categories