0

I want to capture the user name on the start of the session, for that I created a userName state in react and prompt alert to capture the user name.

I have been using set state to set a value which is captured on the start of the session, using the prompt alert but the state is still empty. Its like it is getting recreated again and again, but state are created at the first render only right?

function App() {
  const [chatData,setChatData]=React.useState([]);
  const [userName,setUserNam]=React.useState('');

if(userName==='' || null===userName){
 let user= prompt('Please Enter your Name')
  if (user === null || user === "") {
    console.log("User cancelled the prompt.");
  }
  else{
    setUserNam(user,()=>{console.log("userName- ",userName)})
    console.log("userName- ",userName)
  }
  console.log(userName)
}

but my **userName **is not getting updated. I tried same with use effect still not getting the result.

React.useEffect(()=>{
  console.log("userName- ",userName)
  while(userName===''){
  let user = prompt('Please Enter your Name')
  if (user === null || user === "") {
    console.log("User cancelled the prompt.");
  }
  console.log("user- ",user)
  setUserName(()=>{return('aaaaa')})
  console.log("Name- ",userName)
    }
},[])

Not able to find the solution for capturing user name on the start of the application.

0 Answers0