Cant access store with mapStateToProps - javascript

Im new to react, I'm trying to setup the login system with redux. In my Login component I'm using mapStateToProps with the connect method that react-redux offers.
When I tried to get what I needed from the store It kept saying that it was undefined. This is a snippet of my Login component:
function mapStateToProps(state) {
return {
loggingIn: state.authentication.loggedIn,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(userActions, dispatch),
alertActions: bindActionCreators(alertActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Login)
Here's how I tried to combine reducers:
import { combineReducers } from 'redux';
import authentication from './userReducer';
import alert from './alertReducer'
const rootReducer = () => combineReducers({
authentication,
alert
});
export default rootReducer;
However I couldn't access the logginIn props in the Login component. After trouble shooting for some frustrating hours I got it to work by removing the arrow function to this:
const rootReducer = combineReducers({
Can someone tell me why the arrow function didn't work? Thanks
Update: Here's how I imported the root reducer in the 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 { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk';
import rootReducer from './reducers'
const store = createStore(rootReducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, 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.
serviceWorker.unregister();

The docs tells you to call combineReducers to provide the root reducer.
The createStore method expects a reducer, not a function to call to get this reducer.

In addition to Vinicius' answer, you can refactor your combineReducers() call even more.
Instead of:
const rootReducer = () => combineReducers({
authentication,
alert
});
export default rootReducer;
which I have seen others do before, I guess personally the less code I need to write the cleaner, as long as it doesn't become esoteric looking, anyway just write it like this:
export default combineReducers({
authentication,
alert
});
You export and call the combineReducers() all in one go. Oh and to import it, since we removed rootReducer just do:
import reducers from "./reducers";
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
composeEnhancers(applyMiddleware(reduxThunk))
);

Related

Recieving 'Attempted import error" message in first MERN application

This is my first application I am building with the MERN stack and currently I am going through a tutorial. For some reason I cannot figure out the message :
Attempted import error: 'reducers' is not exported from './reducers'.
This is currently my code in my App.js:
import React from "react";
import ReactDom from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import { reducers } from "./reducers";
import App from "./App";
const store = createStore(reducers, compose(applyMiddleware(thunk)));
ReactDom.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
In the reducers file:
posts.js
export default reducers = (posts = [], action) => {
switch (action.type) {
case "FETCH_ALL":
return action.payload;
case "CREATE":
return posts;
default:
return posts;
}
};
index.js
import { combineReducers } from "redux";
import Post from "./posts";
export default combineReducers({ posts });
to get a better visual this is currently my screen:
computer screen
In your reducers/index.js, you are exporting it as default. Therefore, if you want to import it in your src/index.js, you need to use import reducers from "./reducers" (with no curly braces).
Another approach is that you can use export const reducers = combineReducers({ posts }); in reducers/index.js, then you don't need to modify src/index.js.
You can read more about the document on export in JavaScript.

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

Is this the correct way to implement middleware in redux?

I am attempting to debug a redux store for async actions. But I am failing to pass dispatch as a function so I will be posting series of questions to help myself find my issue. The first thing I need to ensure is that I am applying redux-thunk properly. So is this the correct way to implement redux middleware?
import { createStore,applyMiddleware,combineReducers,compose } from 'redux';
import thunk from 'redux-thunk';
import {createLogger} from 'redux-logger';
import {inventoryFilter,availableAttributes} from '../reducers/reducer';
const logger=createLogger()
const Store = createStore(
///combine imported reducers
combineReducers({
activeFilter:inventoryFilter,
availableAttributes:availableAttributes
},{},applyMiddleware(thunk,logger)
));
export default Store;
No. You're passing the middleware enhancer as an argument to combineReducers, when it should actually be an argument to createStore.
Here's how I would write it:
import { createStore,applyMiddleware,combineReducers,compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';
import {inventoryFilter,availableAttributes} from '../reducers/reducer';
const rootReducer = combineReducers({
activeFilter:inventoryFilter,
availableAttributes:availableAttributes
});
const loggerMiddleware = createLogger();
const middlewareEnhancer = applyMiddleware(thunkMiddleware, loggerMiddleware);
const store = createStore(rootReducer, middlewareEnhancer);
export default store;

Actions must be plain objects while using redux thunk

I am using Redux thunk to dispatch multiple actions.
I have a store.js file
// store.js
import rootReducer from '../reducers/setInitData'; // reducer file
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const middleware = applyMiddleware(thunk);
export default createStore(rootReducer, middleware, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
I have an app.js
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import CampaignCreate from './CampaignCreate' // component
import store from './store/store' // store.js
store.dispatch((dispatch) => {
dispatch({
type: 'SET_STATE',
payload : {
}
})
dispatch({
type : 'DISPLAY_REACT_COMPONENTS',
payload : {
dataLoadComplete : true
}
})
});
render(
<Provider store={store}>
<div id="campaign-init">
<CampaignCreate />
</div>
</Provider>,
document.getElementById('campaigns-react')
)
When I run my code I see the following error in my console:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
What is going wrong with the above code?
It's not the correct way to configure middlewares with redux devtools, according to redux devtools' readme, you should do this:
// don't forget import { compose } from 'redux'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(middleware));

Redux Devtool (chrome extension) not displaying state

I am new with Redux and newer with Redux devtool.
I made a simple app in which you click on a user and it display some data about him.
So basically in the state I have the current selected user.
But I don't know why the state keep beeing empty in redux devtool. (not in the app)
Here is where I create my store :
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
And here is the action :
export const USER_SELECTED = 'USER_SELECTED'
export function selectUser(user){
return {
type : USER_SELECTED,
payload : user
}
}
Here is a reducer :
import {USER_SELECTED} from '../actions/index'
export default function (state = null,action){
switch(action.type){
case USER_SELECTED :
return action.payload
}
return state
}
And finally a call to the action :
this.props.selectUser(user)
The app works very well but I am probably missing something.
Thanks for your help !
Try the following if you have setup the store using a middleware
import { createStore, applyMiddleware, compose } from 'redux';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, /* preloadedState, */ composeEnhancers(
applyMiddleware(...middleware)
));
Did you add this line to your store?
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
github.com/zalmoxisus/redux-devtools-extension#11-basic-stor‌​e
I was looking at how I did it years ago and this would do the trick:
const store = createStore(reducers,
window.devToolsExtension && window.devToolsExtension()
)
For potential redux newcomers working on older projects/tutorials know that
window.devToolsExtensionis deprecated in favor ofwindow.REDUX_DEVTOOLS_EXTENSION`, and will be removed in next version of Redux DevTools: https://git.io/fpEJZ
as previously answered, replace with window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
I tried everything but still Redux was not showing in dev tools,
so I tried this chrome extension. Also reload after installing this extension.
https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd/related?hl=en
It worked like a charm
Also the files,
store.js
import { createStore, applyMiddleware } from "redux"; // importing redux,redux-thunk(for my own use) and redux-devtools-extension
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
const initialState = {}; // declaring the variable with empty state
const composeEnhancers = composeWithDevTools({});
const store = createStore( // creating the store
finalReducer,
initialState,
composeEnhancers(applyMiddleware(thunk)) // you can leave this as it is if no middleware
);
App.js
import { Provider } from 'react-redux'; // importing the provider and store
import store from './store' // using store
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
I was facing the same issue.
I didn't get permanent solution yet but here is the workaround -
Change the chrome DevTools theme, only once it is required.
Now open devtools, you find the extension tab in DevTools.
You can again change the theme whatever you want to keep and this will fix your problem.

Categories