Export Values from Components through Sinks in Cycle.js

André Staltz
InstructorAndré Staltz
Share this video with your friends

Social Share Links

Send Tweet

Our app is not yet a BMI calculator, because it only has two sliders, but doesn't show the calculated BMI number. In this lesson we will learn how to export any stream from a child component and use it in the parent component, in order to display the BMI calculation on the DOM.

[00:01] Our application has two sliders, but it's not yet the BMI calculator. It doesn't show the calculated BMI number. Let's build that next. We need to make the string called BMIstring, which is the number of BMI changing over time.

[00:17] Let's imagine that we have this somehow. We don't know yet how it's going to be, but if we do have it, then we can combine it with the virtual DOM streams, and we can map them to get that value, and put it in a header like this.

[00:35] How do we calculate the BMI string? We know that it needs to come from weight and height numbers. Once we have weight value stream, which is a stream of numbers, and height value stream, then we can combine them. We can use a formula to get the number of weight and height, and calculate the BMI.

[01:00] It all depends on having weight value stream and height value stream, which are streams of numbers. We know that the number should come from the slider changing over time, so the slider component needs to provide that to us.

[01:17] If you look at weight sinks, it originally came from this sinks object, and we don't have there that number stream. How do we get that? The state object here had that value, number, there for us, so we just need to extract that, and we're able to create that stream for us.

[01:39] We're going to return a new stream called value, which will be state stream mapping each state object to state.value. Now, this gives us a stream of numbers representing each slider value over time.

[01:55] Now, under weightsinks.value, we have that stream. Also, under heightsinks.value, we have that stream. This is how our program still works. It has two sliders, and the BMI number is calculated through this stream and displayed on the DOM.

[02:15] Now, we have basically completed our BMI calculator with independent components. The conclusion here is that we can use the sinks here to perform effects to the outside world, but we can also pass basic values from the child component labeled slider to the parent component, which is main here.

[02:38] Usually sinks are meant for the write effects, such as the DOM write effect, but they might also mean simply messages passed up to the parent. The DOM write effect is being combined from these two children to create one DOM write effect here from main. Also, we can use the value sinks to create a n new stream here, which is basically representing state.

[03:09] This is how you get component hierarchy in Cycle.js, and you can pass messages down and up with streams only.