Josue Muleshi
Josue Muleshi

Reputation: 72

"@Composable invocations can only happen from the context of a @Composable function"

@Composable
fun CategorySection(context: Context) {
    Column(modifier = Modifier.padding(8.dp)) {
        Text(
            text = "Api Data",
            style = MaterialTheme.typography.h5,
            modifier = Modifier.padding(vertical = 7.dp, horizontal = 8.dp)
        )
        val coroutineScope = rememberCoroutineScope()

        coroutineScope.launch(Dispatchers.Main) {
            val response = ApiPhoto.apiService.getPhotos()

            if (response.isSuccessful && response.body() != null) {
                val photos = response.body()
                photos?.let {
                    CategoryItemSection(it)
                }
            } else {
                Toast.makeText(
                    context,
                    "Error Occurred: ${response.message()}",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }
}

@Composable
fun CategoryItemSection(photos: List<Photo>) {
    LazyColumn(
        modifier = Modifier.fillMaxWidth()
    ){
        items(photos.size){
            CardView(photos[it])
        }
    }
}

Upvotes: 2

Views: 545

Answers (1)

Johann
Johann

Reputation: 29867

You cannot call CategoryItemSection from inside a coroutine. Your coding practice here is totally wrong. You shouldn't be making API calls to your data sources from within your composables. Use a viewmodel and state hoisting:

Read up on state hoisting and uni-directional data flow:

https://developer.android.com/jetpack/compose/state

Upvotes: 1

Related Questions