-1

Well, I am trying to set the state of my App.js Component in the login.js component to true. The code I have in my App.js is this:

state = {
  isAuth: false
};

And this is how I try to set the isAuth to false in my login.js Component:

    statusCode:{
            200:  function(){
                this.App.state.isAuth = true;
                console.log('it's working!')
            }
        }

This is how I import the App Component: import App from './App';

If the user successfully login the status code should be 200 and after receiving this status code the isAuth of the App.js component should be set to true. Don't know why this is not working. I'm getting the error TypeError: Cannot read property 'state' of undefined.

  • Do you mean to change value of ```isAuth``` to ```false```? –  May 13 '21 at 12:44
  • You probably didn't initialize `this.App`. You can use `React.createRef()` to create ref. But I think this design is problematic. Why don't you get state change via callback of login.js and set the state in App.js. – Kao May 13 '21 at 12:44

1 Answers1

0

It's not possible to setState directly from another component. So, one solution is to pass a function that handles the setState to the other component. For example, in your case:

App.js

import Login from "path/to/Login"

class App extends Component {
  state = {
    isAuth: false
  }

  handleIsAuthChange = (isAuth) => {
    this.setState({ isAuth })
  }

  render () {
    return <Login handleIsAuthChange={this.handleIsAuthChange} />
  }
}

Then you can access the function by props

Login.js

class Login extends Component {
  setIsAuth = (isAuth) => {
    this.props.handleIsAuthChange(isAuth)
  }
  
  // Your Code...
}

Another possible solution is to use the Context API, but this is certainly the easiest way to do it.

If you're still a little lost on this, I recommend you to take a look at this answer as well https://stackoverflow.com/a/55028734/11194008

Dharman
  • 30,962
  • 25
  • 85
  • 135
tavin-dev
  • 321
  • 3
  • 10
  • Well, I have watched the link you posted but I'm still lost. May you please show me in my code what I have to do to set isAuth=true in the login.js component – masterYoda May 13 '21 at 13:10
  • Can you add the code snippet from `App.js` and `Login.js` please? – tavin-dev May 13 '21 at 13:14
  • @masterYoda: You need to study react a bit more. Your mental model of how this works is making you confused. In your original code snippet you want to make this work as `this.App.state.isAuth=true`. Which not how this works. You have to lift the state up and then perform your login activity there and pass is Auth as a prop to your App component. – AdityaParab May 13 '21 at 13:18