Is there any way to stop calling a function multiple times?

Viewed 130

Hi I'm new to react native and been trying to make a hangman app using react native. What I'm trying to do is to make a state in which I save random words and have textInput below, so that the state can compare what you type in textInput and show the matching letters. Otherwise it would just show ' _ ". But the problem is every time I type a letter in textInput, random words are picked out. I want to keep a word until I finish typing up every spelling of the word. It seems like a function I made is called whenever I type a letter, but my programming skill isn't that good enough to pick a problem and fix yet. I've tried moving 'selectedWord' and some googling, which weren't successful. I'm attaching my code below. Hope someone can give me some advice!

const Words = () => { 
   const words = ['app', 'program', 'interface'];
   const [correctLetters, setCorrectLetters] = useState([]);
   let selectedWord = words[Math.floor(Math.random() * words.length)];
   function displayWord() {
      return (
        <Text>
         {selectedWord
           .split("")
           .map(letter => {
             if(letter === " ") {
               return letter;
             } else {
               return correctLetters.includes(letter) ? letter : " _ ";
             }
           })
           .join("")}
         </Text>
       );
     }
     return (
      <View>
        <Text>{displayWord()}</Text>
        <TextInput
          value={correctLetters}
          onChangeText={(e) => setCorrectLetters(e)}
        ></TextInput>
      </View>
     );
   };
1 Answers

You can refactor your code as follows

const displayWord = ({ selectedWord, correctLetters }) => {
  return (
    <Text>
      {selectedWord
        .split("")
        .map((letter) => {
          if (letter === " ") {
            return letter;
          } else {
            console.log(correctLetters);
            return correctLetters.includes(letter) ? letter : " _ ";
          }
        })
        .join("")}
    </Text>
  );
};
const DisplayWord = React.memo(displayWord);

const words = ["app", "program", "interface"];

const Words = () => {
  const [correctLetters, setCorrectLetters] = useState([]);
  const [selectedWord, setSelectedWord] = useState("");
  useEffect(() => {
    setSelectedWord(words[Math.floor(Math.random() * words.length)]);
  }, []);
  return (
    <View>
      <DisplayWord
        selectedWord={selectedWord}
        correctLetters={correctLetters}
      />
      <TextInput
        value={correctLetters}
        onChangeText={(e) => setCorrectLetters(e)}
      />
    </View>
  );
};

Related