Issue
I have this :
const [debugStr, setDebugStr] = useState("This is a debug string")
function debug(str){
setDebugStr(str+'\n\n'+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.
Solution
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 + '\n\n' + prevDebugStr);
}
Answered By - jacorl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.