Access state inside a processor

Roadmap Card

Description

We need a way to access state inside processors because sometimes you don’t want to use a React component, like in the case of styling with the css prop: Styling the HTML content with the `css` prop, but you still need to access state.

User Stories

As a Frontity developer
I want to access state in my processor
so that I can use settings stored in state

Possible solution

There are some possible solutions, like:

  1. Pass state to processors in a non-reactive way.
  2. Connect the Html2React component and observe the processors as a whole. If some observed part of the state changes, rerender the whole Html2React component.
  3. Connect each processor individually with HOC’s.

After a discussion with @orballo, @David, and @iamuchejude we decided to try 1 first and leave 2 and 3 as future optimizations, as long as we maintain the API for backward compatibility.

We agreed that this API makes more sense:

const myHandler = {
  test: ({ node, state, root, libraries }) => { ... }
  process: ({ node, state, root, libraries }) => { ... }
};

We can take the opportunity to pass libraries as well. I don’t think using actions inside processors is a good pattern, if you need that you’d have to create a React component.

The current API is:

const myHandler = {
  test: node => { ... }
  process: (node, { root }) => { ... }
};

So to make it backward compatible we have to try this:

// Convert node to an object, but keep it as it is.
node.node = node;
node.state = state;
node.libraries = libraries;
node.root = root;

// Run tests.
isMatch = tester(node);
// Or processors.
const processed = process(node, { root });

// Remove everything before adding it to the DOM.
delete node.node;
delete node.state;
delete node.libraries;
delete node.root;

It’s going to be a bit weird for people debugging it, but we can release a v2 Html2React version in 6 months that is 100% compatible with v1 as long as you changed this.

If it’s not possible, then we’ll have to release a v2 of Html2React.

This was finally implemented here: frontity/frontity#327

  • Processors’ API was changed and now they receive node, state, root and libraries in both the test and the processor functions.

    const myHandler = {
      test: ({ node, state, root, libraries }) => { ... }
      processor: ({ node, state, root, libraries }) => { ... }
    };
    
  • process attribute was renamed to processor due to an error in generated ES5 bundles (see discussion here)

  • The Html2React component rerenders whenever the state accessed by the processors changes.

  • Processors are backward compatible with the old API.

2 Likes