yasu
yasu

Reputation: 23

A state is undefined object when using React and Redux , Router

Im developing apps with React and Redux , Router. But now I can't set(update) a state into the state of 'mapStateToProps' function. So a reducer's args 'action' is 'undefined'. I think the cause of this problem is that mapStateToProps's args is not passed from anywhere.

Does anyone know how to pass a state(data input from client) into mapStateToProps function?

My mapStateToProps function is simply written like this.

const mapStateToProps = state=>{
console.log(state);  // this 'state' return undefined.
return {
loginform: state
}};

export default connect(mapStateToProps)(LoginForm)

Here is my code.

Index

/index.js

let store = createStore(showUsername,
window.devToolsExtension && window.devToolsExtension() );

ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
    <Route component={AppNavBar}>
        <IndexRedirect to='/login'>
        <Route path='/login' component={LoginForm} />
    </Route>
</Router>
</Provider>
,
document.getElementById('root')
);

Component

/Loginform.js

class LoginForm extends Component {
    ...
}

const mapStateToProps = state=>{
console.log(state);  // this 'state' return undefined.
return {
    loginform: state
}};


export default connect(mapStateToProps)(LoginForm)

ActionCreator

/actioncreator.js

    export const showusername = 'showUsername';

    export const showUsername =(username,index)=>{
    console.log(username,index);
    return{
        type:showusername,
        username,
        payload:index
    }

    };

#Reducer

/reducer.js

    const initialState = {
            username: '',
            password: '',
            submit: false,
            //request: 'self',
            showselectfield: false
        };

    export default function showUsername(state = initialState, action) {
    switch (action.type) {
      case type.showusername:
      return (
          Object.assign({},initialState ,{username:action.username,password:action.password})
          );

    default:
      return state
  }
}

Thanks,

Upvotes: 2

Views: 823

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

In your reducer when you check for the action that was triggered, you are checking for type.showusername but since you already have action.type in the switch case you should check for simply the string value i.e. "showusername"

const initialState = {
            username: '',
            password: '',
            submit: false,
            //request: 'self',
            showselectfield: false
        };

    export default function showUsername(state = initialState, action) {
    switch (action.type) {
      case "showusername":
      return (
          Object.assign({},state ,{username:action.username,password:action.password})
          );

    default:
      return state
  }
}

Upvotes: 0

Related Questions