Home > Software design >  React Native - State doesn't change correctly on button press (TouchableHighlight)
React Native - State doesn't change correctly on button press (TouchableHighlight)

Time:09-03

i want to change a state after a button press on a touchableHighlight component. The problem is that the state doesn't update immediately, but it does after i press another one of the rendered components, and it adds the previous letter to the state. This is the code:

export default function App() {

  const [word, setword] = useState('');
  const handleChange=(e) => {
    setword(word.concat(e.target.outerText));
  };

  return (
    <View style={styles.container}>
      <View style={styles.row}>
      {wordpuzzle.square[0].map((letter, index) => {
        return(
          <TouchableHighlight style={styles.touchableHighlight} key={index} onPress={handleChange}>
            <View style={styles.button}>
              <Text style={styles.text}>{letter}</Text>
            </View>
          </TouchableHighlight>
        )})
      } 

This is the wordpuzzle.json file from where I'm mapping stuff to render inside components.

{
    "square": [
        ["P", "E", "R", "E"],
        ["I", "U", "B", "A"],
        ["T", "A", "B", "L"],
        ["E", "H", "C", "I"]
    ],
    "10": ["pubblicati"],
    "9": ["pubbliche", "pubblicai"],
    "8": ["pubblica"],
    "7": ["pubiche", "barbuta", "barbuti", "barbute"],
    "6": ["pubica", "rubati", "rubate"],
    "5": ["barbe", "beare"],
    "4": ["pere", "pera", "erba", "bali", "pube", "pubi", "bare",
        "taci", "aura", "aure", "ruba"
    ],
    "3": ["eta", "pia", "pie", "che", "ali", "bea"]
}

CodePudding user response:

Might try using previous value in setting state based on previous state

setword(prev => prev.concat(e.target.outerText));

CodePudding user response:

Please try it!

setword([...word.concat(e.target.outerText)]);

Word state is char array. when you call setWord, word content would be added but word variable address itself doesn't change, the system doesn't recognize state changing so UI component doesn't refresh. Basically you should call setWord with a new array.

  • Related