How to use input values for computation in an Observable doc?

I want to create a “dashboard” that’s an interactive graph, driven by sliders, as an observable project (not a notebook). To prototype that, I made a slider, and tried to display twice its value.

Here is a simple doc:

```js

const x = view(Inputs.range());
console.log("x", x);

const x2 = 2 * x;
```

<p>
Here is x: ${x}.
Here is x2: ${x2}
</p>
```

The output has x, but not x2.

How do I write code that has a variable that depends on x?

(Ultimately I’ll use this code to control a graph.)

It’s hard to tell because the forum messed up the formatting a bit. In the future you can wrap code that has backticks in it it with a ~~~ before and after the code:

~~~
like this
~~~

I think that what you have now is

```js
const x = view(Inputs.range());
console.log("x", x);

const x2 = 2 * x;
```

Here is x: ${x}. Here is x2: ${x2}

Observable’s reactive updates only work between blocks. When one of the outputs of a block changes, any dependent blocks will re-run. Since x2 is defined in the same block as x, it isn’t re-computed when x changes.

Instead, you should use something like

```js
const x = view(Inputs.range());
```

```js
const x2 = 2 * x;
```

Here is x: ${x}. Here is x2: ${x2}

Because x2 is in a separate block than x, it will receive reactive updates.

1 Like

That works. Thank you!

I don’t know how I would’ve learned that. It would be useful to put it early in the Framework docs, but I don’t even know where to file an issue for it.

It’s documented on this page in the docs, which is admittedly pretty deep: JavaScript: Reactivity | Observable Framework

Mike has a draft PR open where he is working on reorganize the docs. One of the things he already has done is moving this page up to the top level of the docs. Hopefully that would make it easier to find.

1 Like