I want to change the state of setArray but I cant change it. The console.log shows empty array. The other states are working but not this I've used useEffect too but nothing is happening. Kindly give me a solution.
import React from 'react';
import { Link} from 'react-router-dom'
import {useEffect} from 'react';
const Register = () =>{
const classes = useStyle();
const [name, setName] = React.useState('');
const [password, setPassword] = React.useState('');
const [array, setArray] = React.useState([])
const submit = (event) =>{
const obj = {}
event.preventDefault();
if(array.length === 0){
localStorage.setItem('name', name);
localStorage.setItem('password',password);
localStorage.setItem('array',JSON.stringify(array))
obj.id = Math.random();
obj.name = localStorage.getItem('name');
obj.password = localStorage.getItem('password');
setArray(array => [...array,obj])
console.log(array);
return alert('You are registered');
}
}
return(
<div>
<div className = {classes.formWrapper}>
<Paper elevation={3} className = {classes.paper} >
<Typography variant="h5" style = {{ textAlign : 'center'}}>Register</Typography>
<form noValidate autoComplete="off">
<TextField id="username" className={classes.textfield} style={{width : '95%'}} value = {name} name = "username" label="Username" onChange = {e=>setName(e.target.value)} />
<br />
<TextField id="password" className={classes.textfield} style={{width : '95%'}} value = {password} name = "password" label="Password" onChange = {e=>setPassword(e.target.value)} />
<br />
<br />
<Link to='/'>SignIn</Link>
<Button variant="contained" color="secondary" style = {{width : '100%'}} onClick = {submit} >Register </Button>
</form>
</Paper>
</div>
</div>
)
}
export default Register;