How to implement Redux DevTools? - redux

This is the index.js
import { createStore, applyMiddleware } from "redux";
import rootReducer from "./reducers/reducers";
const store = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={store(rootReducer)}>
<App />
</Provider>,
document.getElementById("root")
);
To be able to use Redux DevTools I need to add this line of code:
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
I tried this:
import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./reducers/reducers";
const initialState = {};
const middleware = [ReduxPromise];
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
ReactDOM.render(
<Provider store={store(rootReducer)}>
<App />
</Provider>,
document.getElementById("root")
);
But then I get this error: TypeError: store is not a function
What am I doing wrong?

This line is wrong:
store(rootReducer)
You've already created the store, by calling createStore(rootReducer). As the error says, store is not a function, and you can't "call" it. Just pass <Provider store={store}>.
Also, note that our new Redux Starter Kit package can help simplify the store setup process for you.

Related

redux persist localstorage data is vanished by reload

I am using redux persist to store my redux state in local storage. The redux persist is working to store data in localstorage, but when I reload the page the data is gone from local storage and state. Here is link of the repo of project on which I am working https://github.com/bakarfreelancer/jccs-frontend. And The below is my reducer and store Index file.
//Reducer/Index.js
import { configureStore } from "#reduxjs/toolkit";
import { combineReducers, compose } from "redux";
import storage from "redux-persist/lib/storage";
import {
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from "redux-persist";
import thunk from "redux-thunk";
import usersReducer from "./usersReducer";
const persistConfig = {
key: "persistroot",
version: 1,
storage,
};
const rootReducer = combineReducers({ users: usersReducer });
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
export default store;
//
//
//
//Index.js
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "bootstrap/dist/css/bootstrap.css";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import { persistStore } from "redux-persist";
import { PersistGate } from "redux-persist/integration/react";
import store from "./reducers";
let persistor = persistStore(store);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate persistor={persistor}>
<BrowserRouter>
<App />
</BrowserRouter>
</PersistGate>
</Provider>
</React.StrictMode>
);
reportWebVitals();
I want to store the redux state (which is updated after user login) in localstorage or some other storage like cookies. I checked the official documentation and I think my code is same.
The problem is solved by using redux toolkit documentation.
So by implementing the createSlice method for creating my reducers it works perfectly.

Why I get TypeError: store.getState is not a function [duplicate]

Here is my code:
store.js
import {createStore, applyMiddleware, compose} from 'redux';
import {fromJS} from 'immutable';
import {routerMiddleware} from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
const sagaMiddleware = createSagaMiddleware();
export default function configureStore(initialState = {}, history) {
// Create the store with two middlewares
// 1. sagaMiddleware: Makes redux-sagas work
// 2. routerMiddleware: Syncs the location/URL path to the state
const middlewares = [sagaMiddleware, routerMiddleware(history)];
const enhancers = [applyMiddleware(...middlewares)];
const store = createStore(createReducer, fromJS(initialState), enhancers);
// Extensions
store.runSaga = sagaMiddleware.run;
store.asyncReducers = {}; // Async reducer registry
return store;
}
Routes.js
import React from 'react';
import {Route, Router, IndexRoute, browserHistory} from 'react-router';
import {syncHistoryWithStore} from 'react-router-redux';
import store from './store';
import Welcome from './containers/Welcome';
const history = syncHistoryWithStore(browserHistory, store);
const routes = (
<Router history={history}>
<Route path="/">
<IndexRoute component={Welcome} />
</Route>
</Router>
);
export default routes;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {browserHistory} from 'react-router';
import { Providers } from 'react-redux';
import configureStore from './store';
import routes from './routes';
const initialState = {};
const store = configureStore(initialState, browserHistory);
ReactDOM.render(
<Provider store={store}>
{routes}
</Provider>, document.getElementById('main-content')
);
I can't find where the culprit is. I tried to debug it, but can't found what really make it those error. error: Uncaught TypeError: store.getState is not a function
Any solution?
This is a typo that generated the error: TypeError: store.getState is not a function
Wrong
const store = createStore(()=>[], {}, applyMiddleware);
Correct
const store = createStore(()=>[], {}, applyMiddleware());
Notice the added parenthesis () on applyMiddleware.
in my case i got this error because my store was as shown below which is a function:
const store = preloadedState => {
let initialState={}
//some code to modify intialState
return createStore(reducer, initialState)
}
but in index.js i was passing store as a function and not the value it was returning.
wrong
<Provider store={store}>
<MyApp />
</Provider>
correct
<Provider store={store()}>
<MyApp />
</Provider>
Notice that in your Routes.js the store is not being initialized properly. You should add these lines:
const initialState = {};
const store = configureStore(initialState, browserHistory);
as in your index.js file.
I was doing this (a dynamic require) ..
const store = require('../store/app')
state = store.getState()
but for some reason when using require instead of import you have to do this ..
const store = require('../store/app')
state = store.default.getState()
Not sure if this will help but you named your import { Providers } instead of { Provider } from react-redux library.
In index.js we have to provide store() method as props value instead of store.
<Provider store={store()}>
{routes}
</Provider>
Updated index.js file.
import React from 'react';
import ReactDOM from 'react-dom';
import {browserHistory} from 'react-router';
import { Providers } from 'react-redux';
import configureStore from './store';
import routes from './routes';
const initialState = {};
const store = configureStore(initialState, browserHistory);
ReactDOM.render(
<Provider store={store()}>
{routes}
</Provider>, document.getElementById('main-content')
);
this is the solution, good luck 🤞
import { applyMiddleware, combineReducers, createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from 'redux-thunk'
const reducer = combineReducers({
products: []
})
const middleware = [thunk]
const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(...middleware))
)
export default store
TypeError: store.getState is not a function -This error often occurs when you are not properly initializing middleware function. What you need to do is as below
You need to add paranthesis on applyMiddleware ( ) function and then it will behave as you are expecting it to do.
const store = createStore(()=>[], {}, applyMiddleware());
Replacing store with store() worked for me. Written below:
<Provider store={store()}>
{routes}
</Provider>

A module cannot have multiple default exports.ts(2528)

I'm trying to implement switch case for my products in Redux. I'm importing the cases from a file named productConstants using multiple export defaults. Problem is, the moment I write multiple lines, my screen turns red with this error 'A module cannot have multiple default exports.ts(2528)'
productReducers.js file
ALL_PRODUCTS_REQUEST,
ALL_PRODUCTS_SUCCESS,
ALL_PRODUCTS_FAIL} from '../constants/productConstants'
export const productsReducer = (state ={ products: [] }, action => {
switch(action.type) {
default:
return state;
}
})
my productConstants.js file
```export default ALL_PRODUCTS_REQUEST = 'ALL_PRODUCT_REQUEST'
export default ALL_PRODUCTS_SUCCESS = 'ALL_PRODUCT_SUCCESS'
export default ALL_PRODUCTS_FAIL = 'ALL_PRODUCT_FAIL'
export default CLEAR_ERRORS = 'CLEAR_ERRORS'
here is my store.js file
```//import { configureStore } from '#reduxjs/toolkit'
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension'
const reducer = combineReducers({
})
let initialState = {}
const middleware = [thunk];
const store = createStore( reducer, initialState, composeWithDevTools(applyMiddleware(...middleware)))
export default store;
and finally, my index.js file
```import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
How do I do away with this error? A module cannot have multiple default exports.ts(2528)
productConstants.js(1, 1): The first export default is here.
A module can have only one default export per module, meaning that in one JS file only one variable (or function) can be exported with the default keyword.
You can convert them all to named export:
export const ALL_PRODUCTS_FAIL = 'ALL_PRODUCT_FAIL'

How can I see my state in Redux Dev Tools (Extension)?

I'm having trouble seeing my state in the Redux Dev Tools. I added the code from zalmoxisus into my createStore, but nothing is displayed. In my reducers I'm also returning the state as a default (using switch case) but still nothing is displayed in state. Can anyone help with this?
try this to use this:
window.devToolsExtension ? window.devToolsExtension() : f => f
instead of:
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
import {combineReducers} from "redux";
import gamesReducer from ... //
const rootReducer = combineReducers({
gamesReducer
});
export default rootReducer;
You used rootReducer like this right?
If it is try redux-devtools-extension package, easy to setup.
Try this
import { createStore, applyMiddleware, compose } from 'redux'
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
export const middleware = [thunk]
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
compose(
applyMiddleware(thunk, reduxImmutableStateInvariant()),
window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
),
)
}

How to run redux devtools with redux saga?

Trying to run reduxdevtools with redux saga:
Getting this error:
Error
Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware
This is my jscode:
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
How can I run this devtool with saga? Alternatively what would work otherwise?
codepen
I've used redux-devtools-extension package as described here, redux-devtools-extension documentation.
After adding the package, I've replaced the store definition with this:
const store = createStore(
reducer,
composeWithDevTools(
applyMiddleware(sagaMiddleware)
)
);
Fixed Codepen Link
The previous answer (by trkaplan) uses an imported method composeWithDevTools from 'redux-devtools-extension' package.
If you don't want to install this package, you may use this code (based on the docs):
const composeEnhancers = typeof window === 'object' && window['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'] ?
window['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__']({ }) : compose;
const enhancer = composeEnhancers(
applyMiddleware(thunkMiddleware, sagaMiddleware, /*other middleware*/),
/* other store enhancers if any */
);
const emptyReducer = () => {};
const store = createStore(emptyReducer, enhancer);
This is how you configure your redux, redux-devtool-extension and redux-saga for the real projects..
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../reducers';
import rootSaga from '../sagas';
const configureStore = () => {
const sagaMiddleware = createSagaMiddleware();
return {
...createStore(rootReducer, composeWithDevTools(applyMiddleware(sagaMiddleware))),
runSaga: sagaMiddleware.run(rootSaga),
};
};
export default configureStore;
Incase Compose of Redux is used. Then below code is useful.
Step 1: Add chrome Redux DevTools extension.
step 2: npm install redux-devtools-extension.
import { composeWithDevTools } from 'redux-devtools-extension';
const store = createStore(
reducer,
compose(
applyMiddleware(sagaMiddleware),
composeWithDevTools(),
),
);

Resources