How to read from DataStore Preferences to string?

Viewed 328

Im trying to use datastore inside Composable to read user data but cant read the value as string to put inside Text. That's the datastore

private val Context.userPreferencesDataStore: DataStore<Preferences> by preferencesDataStore(
  name = "user"
)
private val USER_FIRST_NAME = stringPreferencesKey("user_first_name")
suspend fun saveUserToPreferencesStore(context: Context) {
  context.userPreferencesDataStore.edit { preferences ->
    preferences[USER_FIRST_NAME] = "user1"
  }
}
fun getUserFromPreferencesStore(context: Context): Flow<String> = context.userPreferencesDataStore.data
  .map { preferences ->
    preferences[USER_FIRST_NAME] ?: ""
  }

and inside Composable:

@Composable
fun myComposable() {
  var context = LocalContext.current
  LaunchedEffect( true){
    saveUserToPreferencesStore(context )
  
  }
  Text(getUserFromPreferencesStore(context ))
}
1 Answers

so in your code, getUserFromPreferencesStore() is returning a Flow. so you should collect that as flow, and then compose will auto update once the data is being changed. For example (something similar to this):

val user by getUserFromPreferencesStore(context).collectAsStateWithLifecycleAware(initValue)
Related