Enrico
Enrico

Reputation: 830

Redux Action does not recognize the state

I have been building a React and Redux app. I created a simple container and an action creator which carries an action with a simple console.log() one of the users I have written down in the state (reducer).

The problem is, when I click on the rendered state, it says 'user' is not defined. Why? What can I do to let the function recognize the state?

Container

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


class UserList extends Component {

renderUser() {  
    return <div onClick={this.props.selectUser(user)}>
             {this.props.users[0].giovanni}
              </div>
           }


    render() {
        return (
            <div>{this.renderUser()}</div>
        );
    }
}


function mapStateToProps(state) {
    return {
        users: state.users
    }

}


function matchDispatchToProps(dispatch) {
    return bindActionCreators({selectUser: selectUser}, dispatch);
}


export default connect(mapStateToProps, matchDispatchToProps)(UserList);

Action

export const selectUser = (user) => {
    console.log('yo how are you?', user.users[0]);
    return {
        type: 'USER_SELECTED',
        payload: user
    }    
}

Reducer

export default function () {
    return [
        {
        giovanni: 'operaio',
        marco: 'vigile',
        luca: 'esattore',
        }
    ]
}

Index Reducer

import {combineReducers} from 'redux';
import reducerMain from './reducer_main';

const allReducers = combineReducers({
    users: reducerMain
});

export default allReducers;

Upvotes: 0

Views: 220

Answers (2)

user2065736
user2065736

Reputation:

This looks incorrect for a number of reasons

renderUser() {  
  return (
     <div onClick={this.props.selectUser(user)}>
       {this.props.users[0].giovanni}
     </div>
  );
}

onClick receives a function. In all likelihood, you meant the following

    <div onClick={() => this.props.selectUser(user)}>

And not the call to this.props.selectUser by itself.

What is user? It is not defined. I guess you meant

  renderUser() {  
    return (
       <div onClick={() => this.props.selectUser(this.props.users[0])}>
         {this.props.users[0].giovanni}
       </div>
    );
  }

The action must look like this, since the user object is already passed

export const selectUser = (user) => {
    console.log('yo how are you?', user);
    return {
        type: 'USER_SELECTED',
        payload: user
    }    
}

Upvotes: 2

Dimitar
Dimitar

Reputation: 182

You event handler will trigger asynchronous update of the state, so you will most likely not have the value on the same rendering of the component, you can use a default value if it is not set for example: this.props.users[0].giovanni || ''} in case there is not value or a conditional rendering.

Upvotes: 0

Related Questions