简体   繁体   中英

Why is state set to null immediately after setter function defined by useState is called?

I refactored my App.js into a functional component. When I try to login, my currentUser is set to a user, but then immediately set to null. I am confused why currentUser is set to null after it is given value. Is something calling setCurrentUser again to set it to null?

App.js:

const App = (props) => {
    const [ currentUser, setCurrentUser ] = useState(null)
    const [ shoppingCart, setShoppingCart ] = useState([])

    const handleLogin = (email, password, history) => {
        axios({
            method: 'post',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            data: { email, password},
            url: 'http://localhost:3000/api/v1/login'
        })
        .then( res => setCurrentUser(res.data.user))
    }
    console.log('this is currentUser', currentUser)

    return (
          <Switch>
            <div>
              <SideDrawer currentUser={currentUser} setCurrentUser={setCurrentUser}/>
              <div className='App'>
                {/** OTHER ROUTES HERE **/}
                <Route path='/login' render={
                  () => {
                    return (
                      <Login handleLogin={handleLogin} history={props.history} currentUser={currentUser}/>
                    )
                  }
                    } />
                {/* Route to Signup page */}
                <Route path='/signup' render={
                  () => {
                    return(
                      <SignupForm setCurrentUser={setCurrentUser} history={props.history}/>
                    )
                  }
                } />

              </div>
            </div>
          </Switch>

Login.js

const Login = ({history, handleLogin}) => {
    const classes = useStyles()
    const [ values, setValues ] = useState({
        email: '',
        password: '',
        showPassword: false
    })

    const handleChange = e => {
        const { name, value } = e.target
        setValues({ ...values, [name]: value})
    }

    const handleShowPassword = () => {
        setValues({...values, showPassword: !values.showPassword})
    }

    const handleMouseDownPassword = (e) => {
        e.preventDefault()
    }

    return (
        <Box className={classes.container}>
            <h1>Login</h1>
            <FormGroup>    
                <FormControl variant="outlined">
                    <TextField 
                        className={classes.text}
                        variant='outlined'
                        multiline
                        name='email'
                        label="Email"
                        onChange={handleChange}
                    />
                </FormControl>
                <FormControl variant='outlined'>
                    <TextField
                        label='Password'
                        className={classes.text}
                        type={values.showPassword ? 'text' : 'password'}
                        name='password'
                        margin="normal"
                        variant='outlined'
                        onChange={handleChange}
                        InputProps={{
                            endAdornment: (
                                <InputAdornment>
                                    <IconButton
                                        onClick={handleShowPassword}
                                        onMouseDown={handleMouseDownPassword}
                                    >
                                    {values.showPassword ? <Visibility /> : <VisibilityOff />}
                                    </IconButton>
                                </InputAdornment>
                            )
                        }}
                    />
                </FormControl>
                <Button 
                    variant='contained'
                    className={classes.button}
                    onClick={ () => handleLogin(values.email, values.password, history)}
                >
                    Login
                </Button>
            </FormGroup>
        </Box>
    )
}

Something is setting it to null.

Either: .then( res => setCurrentUser(res.data.user))

or SideDrawer or SignupForm are calling setCurrentUser(null) .

If you remove both SideDrawer and SignupForm you can check the functionality of the .then( res => setCurrentUser(res.data.user)) line.

Then add back SideDrawer and see if that is causing it to be set to null. Lastly, add back SignupForm and see if that's the culprit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM