Hi all! Can some explain to me how to get the Cont...
# react
j
Hi all! Can some explain to me how to get the Context.Provider and useContext(Context) working? For me it doesn't really do what I expect from it. I expect that if I call code like this, where I nest the useContext within a Provider call, that useContext will return the value what is within the provider call. However, it shows the initial value there
Copy code
fun main(args: Array<String>) {
    render(document.getElementById("root")) {
        child(App)
    }
}

val SomeContext = createContext(1)

val App = functionalComponent<RProps> {
    SomeContext.Provider(5) {
        typographyH1 {
            +useContext(SomeContext).toString() // Actually shows '1'
        }
    }
}
If I use this:
Copy code
SomeContext.Consumer { value ->
Then the value is indeed '5' but I do not wish to use this, as it will complain that whatever I cannot use hooks within the Consumer {
block
} as it is no longer a functionalComponent
a
I would normally put the useContext call further up, before the DSL for the elements
that would highlight the issue that the context is fetched separately to the value being provided
which I suspect is what is actually going on here- the context for the rendering of App is created with the default value, and the Provider would only provide a value when a subcomponent was rendered in a separate cycle
I don’t think I’ve got the terminology for that right
Using a Consumer as you indicate would make it work, but I think that’s because it’s now splitting up the render into above and below the Consumer element
j
indeed if I add a child, then it looks like it does what I want:
Copy code
fun main(args: Array<String>) {
    render(document.getElementById("root")) {
        child(App)
    }
}

val SomeContext = createContext(0)

val OtherComponent= functionalComponent<RProps> {
    val number = useContext(SomeContext).toString()
    typographyH1 {
        +number
    }
}

val App = functionalComponent<RProps> {
    val (newValue, _) = useState { 15 }
    SomeContext.Provider(newValue) {
        child(OtherComponent)
    }
}
@araqnid thanks for the explanation! 🙂
@araqnid do you per chance know how to use styles with a functional component? 🙂 I try to use withStyles(functionComponant, styleSet) but the output is rather empty
okay maybe I figured that out <-- I indeed figured out how to use the withStyles in conjunction with function components
a
I don’t know about withStyles, sorry