I am currently following this tutorial. I've hit a bit of a snag involving mapStateToProps in the following code:
import React from 'react';
import Voting from './voting';
import {connect} from 'react-redux';
const mapStateToProps = (state) => {
return {
pair: state.getIn(['vote','pair']),
winner: state.get('winner')
};
}
const VotingContainer = connect(mapStateToProps)(Voting);
export default VotingContainer;
Here is the Voting component that's imported:
import React from 'react';
import Vote from './Vote';
import Winner from './winner';
const Voting = ({pair,vote,hasVoted,winner}) =>
<div>
{winner ? <Winner winner={winner}/> :
<Vote pair={pair} vote={vote} hasVoted={hasVoted}/>
}
</div>
export default Voting;
It is supposed to render two buttons from the pair prop. The vote prop is a function that will be executed on click, hasVoted disables buttons when true and winner only renders the winner component as shown.
The state is expected to be an immutableJS map that looks like this:
Map({
vote:{
pair:List.of('Movie A','Movie B')
}
});
Instead I am getting an error saying that state is undefined in the state.getIn line.
The code setting the state is in index:
const store = createStore(reducer);
const socket = io(document.location.protocol + '//' + document.location.hostname + ':8090');
socket.on('state', state => store.dispatch({
type: 'SET_STATE',
state
}));
I have logged store.getState()after setting and it is as expected but undefined in mapStateToProps. I also logged the state variable in above context and it's also as expected.
I also set the state normally and it surprisingly works!:
store.dispatch({
type: 'SET_STATE',
state: {
vote: {
pair: ['Movie A', 'Movie B']
}
}
});
The value of state above is exactly what is received from the server
Lastly here's what my reducer looks like:
import React from 'react';
import {Map, fromJS} from 'immutable';
const reducer = (state = Map(), action) => {
switch (action.type) {
case 'SET_STATE':
return state.merge(action.state);
}
}
export default reducer;
What am I doing wrong?
EDIT: I realised that mapStateToProps is not being called after the store.dispatch(). I went through the docs for the possible reasons mapStateToProps is not being called and it's not one of them.
You reducer doesn't have a default action in switch statement. Which is why even though you mentioned the initial state in reducer params, undefined is returned as store initial state
import React from 'react';
import {Map,fromJS} from 'immutable';
const reducer = (state = Map() ,action) => {
switch(action.type){
case 'SET_STATE': return state.merge(action.state);
default:
return state;
}
}
export default reducer;
Adding the default statement will fix the issue :)
I ended up here too because I had failed to pass my rootreducer function to my createStore method. I had:
const store = createStore(applyMiddleware(...middlewares));
I needed:
const store = createStore(rootReducer(), applyMiddleware(...middlewares));
Related
so I am trying to refactor some code from my previous question:
React: How to update one component, when something happens on another component
So I started digging deep into the existing code template to see how it was implemented.
I found a reducers.js where I added a new reducer: ActiveTenant
import Auth from './auth/reducer';
import App from './app/reducer';
import ThemeSwitcher from './themeSwitcher/reducer';
import LanguageSwitcher from './languageSwitcher/reducer';
import ActiveTenant from './activetenant/reducer';
export default {
Auth,
App,
LanguageSwitcher,
ThemeSwitcher,
ActiveTenant
};
That new reducer is like this:
import { Map } from 'immutable';
import actions from './actions';
import { adalApiFetch } from '../../adalConfig';
const initState = new Map({
tenantId: ''
});
export default function(state = initState, action) {
switch (action.type) {
case actions.SET_TENANT_ACTIVE:
{
const options = {
method: 'post'
};
adalApiFetch(fetch, "/Tenant/SetTenantActive?TenantName="+state.tenantId, options)
.then(response =>{
if(response.status === 200){
console.log("Tenant activated");
}else{
throw "error";
}
})
.catch(error => {
console.error(error);
});
return state.set('tenant', state.Name);
}
default:
return state;
}
}
and actions for that reducer
const actions = {
SET_TENANT_ACTIVE: 'SET_TENANT_ACTIVE',
setTenantActive: () => ({
type: actions.SET_TENANT_ACTIVE
}),
};
export default actions;
Then from the component itself, I need to call the action when a row is selected on the front end, so I have refactored the commented code, into one line.
import React, { Component } from 'react';
import { Table, Radio} from 'antd';
import { adalApiFetch } from '../../adalConfig';
import Notification from '../../components/notification';
import actions from '../../redux/activetenant/actions';
const { setTenantActive } = actions;
class ListTenants extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
fetchData = () => {
adalApiFetch(fetch, "/Tenant", {})
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
const results= responseJson.map(row => ({
key: row.id,
TestSiteCollectionUrl: row.TestSiteCollectionUrl,
TenantName: row.TenantName,
Email: row.Email
}))
this.setState({ data: results });
}
})
.catch(error => {
console.error(error);
});
};
componentDidMount(){
this.fetchData();
}
render() {
const columns = [
{
title: 'TenantName',
dataIndex: 'TenantName',
key: 'TenantName',
},
{
title: 'TestSiteCollectionUrl',
dataIndex: 'TestSiteCollectionUrl',
key: 'TestSiteCollectionUrl',
},
{
title: 'Email',
dataIndex: 'Email',
key: 'Email',
}
];
// rowSelection object indicates the need for row selection
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
if(selectedRows[0].TenantName != undefined){
console.log(selectedRows[0].TenantName);
const options = {
method: 'post'
};
setTenantActive(selectedRows[0].TenantName);
/* adalApiFetch(fetch, "/Tenant/SetTenantActive?TenantName="+selectedRows[0].TenantName.toString(), options)
.then(response =>{
if(response.status === 200){
Notification(
'success',
'Tenant set to active',
''
);
}else{
throw "error";
}
})
.catch(error => {
Notification(
'error',
'Tenant not activated',
error
);
console.error(error);
}); */
}
},
getCheckboxProps: record => ({
type: Radio
}),
};
return (
<Table rowSelection={rowSelection} columns={columns} dataSource={this.state.data} />
);
}
}
export default ListTenants;
However, its not clear to me the relationship between the action and the reducer, if I check the debugger the action is executed, and none parameter is received, but the reducer is never executed.
DO i have to put a dispatch somewhere?, what I am missing in this puzzle?
So the first thing to understand is the Redux Cycle:
Action Creator-->Action-->dispatch-->Reducers-->State
Action Creator: An action creator is a function that is going to create or return a plain JavaScript object knowns as an Action with a type property and payload property which describes some change you want to make on your data.
The payload property describes some context around the change we want to make.
The purpose of an Action is to describe some change to the data inside our application.
The Action Creator is to create the Action.
The dispatch function is going to take in an Action and make copies of that object and pass it off to a bunch of different places inside our application which leads us to the Reducers.
In Redux, a reducer is a function responsible for taking in an Action. Its going to process that Action, make some change to the data and return it so it can be centralized in some location.
In Redux, the State property is a central repository of all information produced by our reducers. All the information gets consolidated inside the State object so our React application can easily reach into our Redux side of the app and get access to all the data inside the application.
So this way the app does not have to go around to each separate reducer and ask for the current State.
So digest that for a couple of minutes and then look at your architecture.
Let's skip over to reducers.
Reducers are called with an Action that was created by an Action Creator. The reducer will take a look at that Action and decide whether it needs to modify some data based on that Action.
So in other words, the job of a reducer is not to execute API requests but to process actions sent to it by the action creator.
So instead of this:
import { Map } from 'immutable';
import actions from './actions';
import { adalApiFetch } from '../../adalConfig';
const initState = new Map({
tenantId: ''
});
export default function(state = initState, action) {
switch (action.type) {
case actions.SET_TENANT_ACTIVE:
{
const options = {
method: 'post'
};
adalApiFetch(fetch, "/Tenant/SetTenantActive?TenantName="+state.tenantId, options)
.then(response =>{
if(response.status === 200){
console.log("Tenant activated");
}else{
throw "error";
}
})
.catch(error => {
console.error(error);
});
return state.set('tenant', state.Name);
}
default:
return state;
}
}
Your reducer should look something like this:
import { SET_TENANT_ACTIVE } from "../actions/types";
const initialState = {
tenantId: ''
};
export default (state = initialState, action) {
switch (action.type) {
case SET_TENANT_ACTIVE:
return {...state, [action.payload.id]: action.payload };
default:
return state;
}
}
Then inside your action creators file, you should have an action creator that looks something like this:
import axios from 'axios';
import { SET_TENANT_ACTIVE } from "../actions/types";
export const setTenant = id => async (dispatch) => {
const response = await axios.post(`/tenants/${id}`);
dispatch({ type: SET_TENANT_ACTIVE, payload: response.data });
};
You also need to learn about Redux project structure because after the above refactor, you are missing how to wire all this up to your component. In your component file there is no connect() function which also requires the Provider tag and you have none of that.
So for this I recommend first of all your set up your folder and file structure like so:
/src
/actions
/components
/reducers
index.js
So inside your index.js file it should look something like this:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware, compose } from "redux";
import reduxThunk from "redux-thunk";
import App from "./components/App";
import reducers from "./reducers";
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
composeEnhancers(applyMiddleware(reduxThunk))
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.querySelector("#root")
So your goal here is to ensure that you get that Provider tag at the very top of your component hierarchy and ensure that you pass it a reference to your Redux store that gets all the reducers loaded up into it.
So above I have created the store and passed it our set of reducers and it will return back to you all your applications State.
Lastly, what you see above is I created an instance of <Provider> and wrapped the <App /> component with it and then you want to pass the <Provider> component is a single prop called store. The store is the result of calling createStore() and calling the reducers.
The <Provider> is what interacts with the Redux store on our behalf.
Notice, I also have wired up Redux-Thunk that J. Hesters mentioned, you are making an ajax request as far as I can see from your code which is why I offered an asynchronous action creator for you, which means you will need Redux-Thunk or some middleware like that, let me not offend the Redux-Saga fans, so you have those two choice at least. You seem relatively new to Redux, just go with Redux-Thunk.
Now you can use the connect() component inside your component file to finish wiring up those action creators and reducers to your component or your React side of the application.
import React, { Component } from 'react';
import { connect } from "react-redux";
import { Table, Radio} from 'antd';
import { adalApiFetch } from '../../adalConfig';
import Notification from '../../components/notification';
import actions from '../../redux/activetenant/actions';
After importing connect, you create an instance of it below:
export default connect()(ListTenants);
Please don't argue with me on the above syntax (actually had a former student report me to administrators for using this syntax as evidence of not knowing what I was doing).
Then you need to configure this connect() React component by adding mapStateToProps if you are going to need it, but definitely pass in actions as the second argument to connect(). If you realize you don't need mapStateToProps, then just pass in null as the first argument, but you can't leave it empty.
Hope all this was helpful and welcome to the wonderful world of React-Redux.
You are using reducers wrong. Reducers are supposed to be pure. Yours has side-effects showing that you haven't understood Redux, yet.
Instead of writing down a solution for you (which would take forever anyways since one would have to explain Redux in total), I suggest you invest the 3 hours and go through the Redux docs and follow the tutorials (they are great).
Afterwards you might want to look into Redux Thunk. But, you might not need thunks.
PS: (Small thing to bring up, but I haven't seen anyone using Maps in Redux. Is there a reason you do that? You might want to use plain objects instead.)
Your action is not correct you should pass an active tenant name as parameter.
Ref. https://redux-starter-kit.js.org/api/createaction
We could have written the action types as inline strings in both places.
The action creators are good, but they're not required to use Redux - a component could skip supplying a mapDispatch argument to connect, and just call this.props.dispatch({type : "CREATE_POST", payload : {id : 123, title : "Hello World"}}) itself.
Ref. https://redux-starter-kit.js.org/usage/usage-guide
Dont recognize my action as a function.
Hello, im setting up a React-Redux application, and i want to centralize the all the set.states of my projects in one unique store.First, i was trying to call an actios that gives me data of an external API (In array form), it worked well in react, and it worked well too in a friends project.
The compiler keeps telling me that the action call method is not a function.
Thanks
Here's the problematic function:
/*imports*/
import { connect } from 'react-redux';
import { getPokeList } from '../../actions/pokeList';
componentDidMount = () => {
const pokeUrl = `https://pokeapi.co/api/v2/pokemon/`;
getPokeInfo(pokeUrl)
.then(data => this.props.getPokeList(data.results)) <---
}
/* connection */
const mapStateToProps = state => ({
pokeList: state.pokeList.elements,
});
export default connect(mapStateToProps, { getPokeList })(List);
Heres my action method:
const GET_LIST = 'GET_LIST';
export default {
GET_LIST,
}
export const getPokeList = list => ({ type: GET_LIST, list });
And here's my reducer:
import pokeList from '../../actions/pokeList'
const initialState = {
list: [],
};
const reducer = (state = initialState, action) => {
if (action.type !== null) {
switch (action.type) {
case pokeList.GET_LIST:
return { ...state, list: action.list };
default:
return state;
}
}
return state;
};
export default reducer;
For the moment i dont use the result data in any part of my code.
Thanks and excuse my english!
In App.jsx you need to change the Link import to:
import List from '../../components/List/List';
After this your reducers will be reached, etc. I made it this far after pulling down your code. I wasn't sure what you were trying to achieve after this, so I left it at that.
Ultimately, the issue you encountered is because you have "export default" in your Link component.
I just wanted to integrate a new Container in my React App, wired it up with Redux and just wanted to see it's all working. It's not however. accessing the reducer via this.props.selection gives me undefined. I don't know why. It does work in other containers, and the reducer has some well-defined initial state. - I'm not sure I see what the difference is here? Am I missing something trivial?
import React, { Component } from 'react'
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
export class AudioPlayer extends Component {
constructor(props) {
super(props);
this.state = { someComponentState : true }
}
onLog() {
console.log("Logging:");
console.log(this.props.selection); // gives me: undefined
}
render() {
return (
<div>
<button onClick={()=> this.onLog()}>LOG</button>
</div>
)
}
}
function mapStateToProps (state) {
return {
selection: state.selection
};
}
export default connect(mapStateToProps)(AudioPlayer);
PS: I've simplified this component somewhat, but I think it should still reflect the problem.
edit: reducer example
people have asked to see the reducer, however, I've tried this with several reducers that are already implemented in the app and are working in other containers, so I don't think this is where the problem lies - but who knows:
import { SELECT_ITEM } from '../actions/types';
export default function(state = {}, action) {
switch(action.type) {
case SELECT_ITEM:
return {...state, error:'', selected: true};
}
return state;
}
edit2: mapStateToProps does not seem to be called at all
I just tried to do a console.log in mapStateToProps, to see if it's called, and seems that it never is. Nothing is ever logged. What could be the reason for this?
function mapStateToProps (state) {
console.log("In map function");
console.log(state);
return {
selection: state.selection, //both return
auth: state.auth // undefined
};
}
I also added another reducer (auth) which works elsewhere in the app, but here returns undefined.
edit3: My Root Reducer
import { combineReducers } from 'redux';
import { reducer as form } from 'redux-form';
//reducer imports
import authReducer from './auth_reducer';
import articlesReducer from './articles_reducer';
import userReducer from './user_reducer';
import currentSelectionReducer from './currentSelection_reducer';
const rootReducer = combineReducers({
auth: authReducer,
user: userReducer,
articles: articlesReducer,
selection: currentSelectionReducer,
});
export default rootReducer;
Can you try removing 'export' from 'export class AudioPlayer extends Component'
you can also check this: mapStateToProps not getting called at all
your component code is fine.
In your reducer it should be
export default function(state = { selected: false }, action) {
Further reading:
https://redux.js.org/recipes/structuringreducers/initializingstate
https://stackoverflow.com/a/37823335/2477619
1) In your debugging please check it enters the exact case in the reducer, that it understands the action.type == SELECT_ITEM, and returns the new state.
2) Also notice selection is an object, which contain the 'selected' inside it.
Your 'selection' reducer contains: {...state, error:'', selected: true}
maybe there is a confusion about this?
I have been trying to figure out how to use combineReducers on the server side following the official document.
Here are two of the reducers I'm trying to combine, but no success:
ListingReducer:
import ActionType from '../ActionType'
export default function ListingReducer ( state = Immutable.List.of(), action){
switch(action.type) {
case ActionType.ADD:
return [
...state,
action.item
];
case ActionType.DELETE:
return state.filter(function(cacheItem){
return cacheItem.id !== action.item.id;
});
default:
return state
}
}
DialogShowHideReducer:
import ActionType from '../ActionType'
export default function DialogShowHideReducer ( state = false, action){
switch(action.type) {
case ActionType.DIALOG:
state = action.visible?false:true;
return state;
default:
return state;
}
}
Store.js (I need to pass some initial data to the listing reducer in order to dynamically add or remove items):
import {createStore} from 'redux';
import { combineReducers } from 'redux';
import ListingReducer from '../reducer/ListingReducer';
import DialogReducer from '../reducer/DialogShowHideReducer';
export default function (initData){
let listingStore = ListingReducer(initData.item,{});
let dialogStore = DialogShowHideReducer(false,{'type':'default'});
// !!!!!!No reducers coming out of this function!!!!!!!!!!
let combineReducer = combineReducers({
listing:listingStore,
dialog:dialogStore
});
return createStore(combineReducer)
}
homepage_app.js
import store from './store/Store'
import CustomComponent from './custom_component';
export default class HomePage extends React.Component {
render() {
<Provider store={store(this.props)}>
<CustomComponent/>
</Provider>
}
}
But what is this reducer failure error about on page load on the client side?
Store does not have a valid reducer.
Make sure the argument passed to combineReducers
is an object whose values are reducers.
The major difference between the official guide and my exmaple is that I pass the initial state to some reducer before passing them to combineReducers.
The problem is that you're actually not passing functions to your combineReducers function. You're passing the result of your reducer functions, when you do something like let listingStore = ListingReducer(initData.item,{});. This sets listingStore equal to the state returned from the reducer function, instead of the reducer function itself.
If you need to pass initial state to your reducers dynamically (i.e. not hard code them into the reducer), Redux provides a preloadedState argument for the createStore function.
So instead of what you did, you'll want to do something like this:
...
let combineReducer = combineReducers({
listing: ListingReducer //function
dialog: DialogShowHideReducer //function
});
let initialState = ... // your initial state here
return createStore(combineReducer, initialState);
...
I created a simple React component for generating menu, and I wanted to replace it's visibility toggling with Redux (instead of state).
My component looks like this:
class SiteMenu extends React.Component {
constructor(props) {
super(props);
}
toggle(force = false) {
let active = !active;
store.dispatch({
type: 'TOGGLE',
active
});
}
render() {
const wrapperClass = this.props.active ? `${this.props.className}__wrapper ${this.props.className}__wrapper--active` : `${this.props.className}__wrapper`;
return (
<nav className={this.props.className} ref="nav">
<button className={`${this.props.className}__trigger`} onClick={this.toggle.bind(this)}>
{this.props.active}
</button>
<ul className={wrapperClass}>
</ul>
</nav>
);
}
}
I added mapStateToProps:
const mapStateToProps = (store) => {
return {
active: store.menuState.active
}
};
and connect
connect(mapStateToProps)(SiteMenu);
My store:
import { createStore } from 'redux';
import reducers from './reducers/index.js';
const store = createStore(reducers, window.devToolsExtension && window.devToolsExtension());
export default store;
and reducers:
import { combineReducers } from 'redux';
import menuReducer from './menu-reducer';
const reducers = combineReducers({
menuState: menuReducer
});
export default reducers;
const initialMenuState = {
active: false
};
const menuReducer = (state = initialMenuState, action) => {
switch(action.type) {
case 'TOGGLE':
console.log(action);
return Object.assign({}, state, { active: action.active });
}
return state;
};
export default menuReducer;
When I check my Redux DevTools, state is changing. What should I do?
Code in the repo: https://github.com/tomekbuszewski/react-redux
to use connect func , also you should add Provider from react-redux
render(<Provider store={store}><Parent /></Provider>, app);
then you should add wrapped component to Parent component
const SiteMenuWrapped = connect(mapStateToProps)(SiteMenu);
///in Parent component
<Header className="site-header">
<SiteMenuWrapped
className="site-navigation"
content={this.state.sections}
/>
</Header>
Few issues:
connect returns a higher order component, so best advice is to split out each component to a separate file and export the result of connect. See the examples at e.g. http://redux.js.org/docs/basics/ExampleTodoList.html. This means that your mapStateToProps function is never being called, hence why this.props.active is always undefined.
Your store registration is incorrect, the second parameter to createStore is the initial state. To register the Chrome Redux dev tools see https://github.com/zalmoxisus/redux-devtools-extension
You should use <Provider> to make the store available to all components. See the Redux docs.
You can dispatch actions through this.props.dispatch or use mapDispatchToProps, see https://github.com/reactjs/react-redux/blob/master/docs/api.md