🏠 back to Observable

Understanding Observable runtime

I’m redoing the tutorial how-to-embed-a-notebook-in-a-react-app about embeding a notebook’s cell in a react app and making communication between the notebook’s module and the react App work.

I succeeded in doing it with the npx create-react-app before the fileAttachement udpate. Today it fails because npx does not enable support for importMeta by default and enabling it is not as straight forward as adding a .babelrc to the App root… Secondly should the link import notebook from "@jashkenas/how-to-embed-a-notebook-in-a-react-app"; should be updated to import notebook from "@observablehq/how-to-embed-a-notebook-in-a-react-app";

Since I’m not using npx create-react-app any more but have my own webpack, babelrc config file I’m not too concerned about the above. But I would like is really understand this part of the tutorial

runtime.module(notebook, name => {
...
      if (name === "mutable speed") {
        return {fulfilled: (value) => {
          this.animationSpeed = value;
        }};
      }
...

I understand that we are applying the name=> function to all the variables defined in the notebook but I don’t get the return value here ? Is it related to observer.fulfilled(value) ? Why are we returning an object whose value is a function ? When do we call that function ?

Thank you.

The object returned here is called a “custom observer” in the docs (see also the part starting “For more control…” here). Its methods are called by the runtime whenever the state of the cell changes, e.g. when the cell returns successfully, then fulfilled is run.

I’m not sure I understand correctly.
Is this is a custom observer watching if the observable mutable speed cell is fullfiled with a new value and then calling the (value)=> to update some React var ?
If it does it at the mounting (first creation) of the component initializing this.animationSpeed variable.

Then each time the component is updated, the following function is called:

  componentDidUpdate(nextProps, nextState) {
    if (nextState.speed !== this.state.speed) {
      this.animationSpeed.value = nextState.speed;
    }
  }

this should update this.animationSpeed.value (the value of the observable ``mutable speed variable) with the nextState.speed that is taken from the user interaction with the interface.

Ok… I think I got it…

The code of how-to-embed-a-notebook-in-a-react-app did not work ‘as is’ for me. I had to make the following adjustment in addition to the one mentioned previously.

Adding the constructor method:

  constructor(props) {
    super(props);
    this.state = { speed: 0.1 };
    this.animationRef = React.createRef();
  }

Thank you @bgchen. Your comment helped me push the reflexion far enought to grasp what I had read without really understanding it.

1 Like