Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compose Snackbar not appearing on repeated error

I am new to jetpack compose and is trying to show an error snackbar whenever the error message I am observing is not null.

Scaffold(scaffoldState = scaffoldState) {
        LaunchedEffect(errorMessage) {
            if (errorMessage != null) {
                scope.launch {
                    scaffoldState.snackbarHostState.showSnackbar(errorMessage)
                }
            }
        }
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
              //some ui components inside here
        }
    }

The issue in the above code is that, the first time the error message changes from null to a particular message it appears fine. However on a repeated user action that produces the same error message it's not coming again.

P.S - I know this is happening due to placing the errorMessage as key inside the LaunchedEffect. My doubt is that, is there a different approach to achieve what I want?

like image 499
Hyzam Avatar asked Nov 02 '25 06:11

Hyzam


1 Answers

This is happening because the LaunchedEffect will run again just in case the errorMessage has changed. What you can do is:

LaunchedEffect(errorMessage) {
   if (errorMessage != null) {
        resetErrorMessage() // reset errorMessage
        scope.launch {
            scaffoldState.snackbarHostState.showSnackbar(errorMessage)
        }
   }
}

The resetErrorMessage must set the errorMessage to null, so the LaunchedEffect will run again, but since you're checking if it is not null, nothing will happen. But as soon you receive a new error message, the LaunchedEffect will be executed again.

like image 121
nglauber Avatar answered Nov 03 '25 22:11

nglauber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!