0
votes

I'm creating a game that user can login with just a username as a guest and play. Normally, when user visits the website I'm fetching all users data from firebase and assigning it to users state and then if user click Play button I'm checking if username exist.

where I fetch all data

 useEffect(() => {
    dispatch(guestInputActions.changeInputValue(randomUser))
    dispatch(fetchUsers()) 

  }, []) 

Where I check if user exsits

const handleGuestLogin =  () => {
    async function checkIfUsernameExist() {
      if (users) {
        const existUser = users.find((user: User) => user.username === inputValue.toLowerCase())
        if (existUser) {
          dispatch(userLoginActions.setLoginStatus(false))
          dispatch(userLoginActions.setErrorMessage("This username already exists!"))
          return
        } else {
          dispatch(userLoginActions.checkUserName(inputValue))

        }
      }
    }
 
   checkIfUsernameExist();

  }

But I don't think it is efficent way. I want to fetch all users data when user click play button not on initial render. But when I try to do that with async/await my users array always empty before I check if username exists. So, user can play game even username is in already database

What I tried to fetch users data when user click Play button (not on initial render)

useEffect(() => {
    dispatch(guestInputActions.changeInputValue(randomUser))
  // dispatch(fetchUsers()) commented out this line

  }, [randomUser])
const handleGuestLogin = async () => {
    async function checkIfUsernameExist() {
      if (users) {
        const existUser = users.find((user: User) => user.username === inputValue.toLowerCase())
        if (existUser) {
          dispatch(userLoginActions.setLoginStatus(false))
          dispatch(userLoginActions.setErrorMessage("This username already exists!"))
          return
        } else {
          dispatch(userLoginActions.checkUserName(inputValue))

        }
      }
    }
   const val = await dispatch(fetchUsers());
   checkIfUsernameExist();

  }
Not sure if I'm overlooking something, but I don't immediately see any calls to a Firebase API in the code you shared. Is the question really about, or do you just happen to be using Firebase and is the question actually just about ReactJS flow? - Frank van Puffelen