Hello everyone,
I am currently developing a Kotlin/JS application for an internal demo, and I’m using the fetch API to call a back-end service that provides weather information. I’ve written the following code to make the API call:
fun weatherApi() = window.fetch("http://localhost:9090/weather")
.then { response -> response.json() }
.then { response -> JSON.stringify(response) }
data class CurrentWeather(
var temperature: Double = 0.0,
var windspeed: Double = 0.0,
var winddirection: Int = 0,
var is_day: Int = 0,
var time: String = ""
)
val Weather = FC<Props> {
val city by useState("Hamburg")
var temperature by useState(0.0)
useEffect {
weatherApi().then { response ->
val currentWeather = JSON.parse<CurrentWeather>(response)
temperature = Object.entries(currentWeather).find { key -> key.component1() == "temperature" }?.component2() as Double
}.catch { error ->
console.error(error)
}
}
div {
+ "The weather in $city is currently $temperature degrees."
}
}
When I try to read the temperature
value directly from the CurrentWeather
object using currentWeather.temperature
, I encounter the following error:
TypeError: currentWeather.get_temperature_j7qf4b_k$ is not a function
In order to retrieve the value from the CurrentWeather
object, I have to use the following code:
temperature = Object.entries(currentWeather).find { key -> key.component1() == "temperature" }?.component2() as Double
I believe I’m missing some information on how to properly parse the JSON response. I have tried referring to the documentation but haven’t been able to find a solution. Could you please help me resolve this issue and correctly parse the JSON response?
Thank you in advance for your assistance.