Connecting
In this section we will explore the three ways available in ConanJs to connect a component with a state. There are four ways of doing it:
Direct
We can use the Conan state object directly to connect to a component, using the method connect. This method will connect the whole state to the specified component
import { counterState$ } from "../../../state/counter.state$";
{counterState$.connect(CounterDisplay)}We can also use connectMap to connect to specific parts of the state:
import { counterState$ } from "../../../state/counter.state$";
counterState$.connectMap(CounterContainer, (data, actions) => ({
decrementCounter: actions.decrement,
incrementCounter: actions.increment
}));
counterState$.connectMap(CounterDisplay, data => ({
counter: data.counter
}))
import {counterState$} from "../../../state/counter.state$";
counterState$.connectMap<CounterContainerProps> (
CounterContainer,
(data, actions)=>({
decrementCounter: actions.decrement,
incrementCounter: actions.increment
})
)
counterState$.connectMap<CounterDisplayProps> (
CounterDisplay,
data=>({
counter: data.counter
})
)HOC
Using the ConanJs component StateConnect, we can connect a React component with a Conan state:
And then use the state's data and actions within our React component. We can also use Conan's component ContextStateConnect, to achieve the same purpose, connect the whole state with a component:
Inside the component, we can invoke the actions defined in the state, via props:
We can also access any data property via props:
Composition
We can also use compositions with the components contextStateConnect and contextStateMapConnect
contextStateConnect will connect the whole state:
contextStateMapConnect will connect only the specified properties:
Hooks
ConanJs has the hooks useConanState and useContextConanState to connect to a state:
Please take a look at this code sandbox to see al the subscription approaches working:
Last updated
Was this helpful?