Learning kotlin/react/redux. Redux doesn't like a...
# serialization
s
Learning kotlin/react/redux. Redux doesn't like a "preloadedState" to be anything other than a plain js object. Sending back an initialized data class makes it complain about expecting an object, not and "Object". This is the best I could figure, is there a better way that I'm missing?
Copy code
package index.store.state

import index.model.User
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration

@Serializable
data class State(val users: Array<User> = emptyArray())

fun state(): State {

    val json = Json(JsonConfiguration.Stable)

    return JSON.parse(
        json.stringify(
            State.serializer(),
            State()
        )
    )
}
It feels cleanish, but it seems like there might/should(?) be a native function I can't find that converts a data class to a kotlin.js.Json object.
t
You can use
DynamicObjectParser
if you need plain JS object
s
That's true, I came across that, but it's "Experimental". I think the main thing I'm trying to avoid is the intermediate string state if possible. One option is to do it like this:
Copy code
import kotlin.js.json

fun state(): State {
    return json("users" to emptyArray<User>()).unsafeCast<State>()
}

interface State {
    val users: Array<User>
}
Which is probably the better option in some ways, but I don't like that typing between the State and its Interface is something I have to maintain.
No
@Experimental
annotation found
s
No I'm not, I'm new to kotlin, when I went to implement it is said I had to annotate the call stack with "@ImplicitReflectionSerializer" and something about experimental.
One sec, I'll get the IDE message
message has been deleted
t
You can define
serializer
(second parameter) to avoid this error
s
Wasn't sure what that meant, and since I'm learning basics right now I left it.
t
You can use second
parse
realization
Copy code
fun <T> parse(obj: dynamic, deserializer: DeserializationStrategy<T>): T
s
Right, ok. Doesn't that deserialize to a data class? Is there a deserializer for kotlin.js.Json class? I am trying to get a plain js object.
t
DynamicObjectParser
can only read JS object 😞
s
That's cool. I appreciate you bringing it up, I had set it aside as experimental, dismissing it too soon.
Thanks for taking the time to help.