skip to Main Content

I have this :

const [debugStr, setDebugStr] = useState("This is a debug string")

function debug(str){
    setDebugStr(str+'nn'+debugStr)
}

function testPressed(){
    debug("Test1")
    debug("Test2")
}

// and later :
<Button onPress={() => { testPressed() }} title='Press me' />
<Text>{debugStr}</Text>

My problem is that only "Test2" is displayed.
I understand that useState is asynchronous and, therefore, it doesn’t update the values on the fly. So, how can I do to be able to call twice a debug function like this one and display each string ?

Thanks.

2

Answers


  1. To display all the debug messages, you can modify your code to accumulate the debug messages and update the state once with the concatenated string. Here’s a way to achieve this:

    function debug(str){
        setDebugStr(prevDebugStr => str + 'nn' + prevDebugStr);
    }
    
    Login or Signup to reply.
  2. You should modify the function to display all debug messages like this;

    function debug(str) {
        setDebugStr(debugString => ([
          str,
          'nn',
          debugString
        ]));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search