user10715317
user10715317

Reputation:

How to change the initial state set in reducer from another component

I have set the initial state in my redux reducer for login auth.Say authError=null on successful login I would like to change it. When I click logout, I want to set authError = ''.

Can I change to readonly state of reducer form a component?

Component

   const {authError} = this.props;
   this.setState(authError = "")

Reducer

 const initState = {
 authError : '',
 empname : 'test', phoneno:'321' 
 }

 const signin = (state = initState, action) => {

switch(action.type){
  case 'SIGN_IN':
    const empname = action.payload.empname;
    const phoneno = action.cred.phoneno;
    console.log('===============$$$=====================');
    console.log(empname, phoneno);
    console.log('===============$$$=====================');
    return {
      ...state,
      authError : null,
      empname,
      phoneno
   }
} 

Upvotes: 0

Views: 882

Answers (1)

Firdous nath
Firdous nath

Reputation: 1587

No you cannot called setState on props. As props are used to customize Component when it’s being created and give it different parameters.

Unlike props, state is a private feature and it strictly belongs to a single Component. State allows React components to dynamically change output over time in response to certain events.

A reducer is a pure function that takes the previous state and an action as arguments and returns a new state.

In short reducer dispatches the application states to suitable components in form of props. If you want to change a value of prop from a component you need to define a separate action and modify value in that action & then you can return modified value .

You can easily get started by reading this

Upvotes: 1

Related Questions