KotlinJS React - Context and Reducer

44 views Asked by At

I am trying to use Context and Reducer, but I just cannot get it to work for hours. I followed this Tutorial: https://react.dev/learn/scaling-up-with-reducer-and-context

A little stripped down and with just a string it looks like this: App.kt

val authContext = createContext<String?>(null)
val authDispatch = createContext<Dispatch<String>>()
val authReducerTask: Reducer<String?, String> = { state, action ->
    println("Reducer called with Action $action")
    action
}
val App = FC<Props> {
    val authReducer = useReducer(authReducerTask, null)
    StrictMode {
        authReducer.let {(state, dispatch) ->
            authContext.Provider(value = state) {
                authDispatch.Provider(value = dispatch) {
                    CssBaseline()
                    RouterProvider {
                        router = appRouter
                    }
                }
            }
        }
    }
}

Main.kt

val Main = FC<Props> {
    val token = useContext(authContext)
    println("Main context: ${authContext.hashCode()}")
    println("Main token: $token")
}

Login.kt

val LoginView = FC<Props> {
    val token = useContext(authContext)
    println("LoginView context: ${authContext.hashCode()}")
    println("LoginView Token: $token")
    location.href = "${environment.SERVER_URL}/login/callback"
}

LoginCallback.kt

val LoginCallback = FC<Props> {
    val token = useContext(authContext)
    val dispatch = useContext(authDispatch)
    println("LoginCallback context: ${authContext.hashCode()}")
    println("LoginCallback Token: $token")
    println("LoginCallback Dispatch: $dispatch")
    dispatch?.let {
        println("Dispatching")
        it("NEW TOKEN")
    }
    location.href = environment.SERVER_URL // back to main.
}

Output:

LoginView context: -208293842
LoginView Token: null
LoginView context: -208293842
LoginView Token: null
LoginCallback context: -1122324025
LoginCallback Token: null
LoginCallback Dispatch: function () { [native code] }
Dispatching
Reducer called with Action NEW TOKEN
LoginCallback context: -1122324025
LoginCallback Token: NEW TOKEN
LoginCallback Dispatch: function () { [native code] }
Dispatching
LoginCallback context: -1122324025
LoginCallback Token: NEW TOKEN
LoginCallback Dispatch: function () { [native code] }
Dispatching
Reducer called with Action NEW TOKEN
Main context: 1918903185
Main token: null
Main context: 1918903185
Main token: null
0

There are 0 answers