skip to Main Content

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"]
}

2

Answers


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

    setword(prev => prev.concat(e.target.outerText));
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search