Home > OS >  How to use array.includes in a promise in React Typescript?
How to use array.includes in a promise in React Typescript?

Time:03-31

The problem I am really having is .includes() method is behaving erratically. I am using it to check if a user entered word is a valid word, like allWords.includes(userWord). It usually returns false, regardless of inclusion of word. allWords is like 12,000 elements or so, I think I need to call it asynchronously.

A simpler version in codesandbox works, but it's always returning false in my react program. I am still new to TS, and async programming. Planning to read a book on it, but want to finish this darn program first.

Here is my async function

//helpers.ts
export async function validateGuess(guess: GuessCharacter[]): Promise<boolean> {

  async function includesPromise(array: string[], word: string) {
    return new Promise<boolean>((resolve) => {
      resolve(array.includes(word));
    });
  }
  
  //each letter of word is in an object
  let word: string = '';

  for (let character of guess) {
    word  = character.value;
  }

  return includesPromise(allWords, word).then((result) => result);
}

Here is where it is called

/// index.ts
  function handleEnterPress() {
    validateGuess(gameState.guesses[gameState.guessCount]).then((response) => {
      if (response) {
        dispatch(ActionKind.Enter);
      } else {
        console.log('Not in word list');
      }
    });

I've also tried

  async function handleEnterPress() {
    let status: boolean = await validateGuess(
      gameState.guesses[gameState.guessCount]
    );
    if (status) {
      dispatch(keyAction.Enter);
    } else {
      console.log('Not in word list');
    }
  }

All help is appreciate. Thanks!

CodePudding user response:

The main issue is that you think this line returns result. It doesn't. It returns the unresolved promise. When the promise gets resolved (because you added a .then() the result is passed in... but then it's lost.

  return includesPromise(allWords, word).then((result) => result);

You could await that to get the value out of the promise. Best to not mix async/await and .then()/.catch().

EDIT: ... and the comments from others are all valid as well.

CodePudding user response:

Your logic looks OK.

A couple of things there:

  1. What does gameState.guesses contain? For your logic to work it should be an array of objects with a property called value which should be an iterable
  2. If gameState.guesses[i] is a string you should NOT do word = character.value but:
    word = character instead
  3. gameState.guessCount should NOT be greater than (gameState.guesses.length - 1) or you will get an undefined value
  4. You don't need to use an async operation there once it's going to be an in-memory operation, you won't be doing it any faster nor going to free processing time for other tasks.
  • Related