Getting infinite loop using cycle-idb with text field for input

119 Views Asked by At

I've been trying to create a simple test app that takes user input from a text field, displays it, and also persists it with cycle-idb. But I keep falling into infinite loops, no matter what I do.

Here's the whole main function:

function intent(domSources) {
  return domSources.select('.name')
    .events('input')
    .map(ev => ev.target.value);
};

function model(input$, db$) {
  const log$ = db$;
  return xs.combine(input$, log$)
    .map(([input, logs]) => {
      return {
        id: 1,
        name: input,
      }
    }).startWith({id: 1, name: ""});
};

function view(state$) {
  return state$.map(log => {
    return (
      <div>
        <label for='name'>Name: </label>
        <input 
          className='name' 
          type='text' 
          value={log.name}
          placeholder="Enter a log name"
        />
        <p>{log.name}</p>
      </div>
    )
  });
};

function persist(state$) {
  return state$.map(log => {
    return $put('logs', log)
  });
};

export function main (sources) {
  const db$ = sources.IDB.store('logs').getAll();
  const input$ = intent(sources.DOM);
  const state$ = model(input$, db$);
  const vtree$ = view(state$);
  const updateDb$ = persist(state$);

  return {
    DOM: vtree$,
    IDB: updateDb$,
  };
}

I'm trying use the MVI and using TodoMVC as an example but I can't figure out how to manage the circular dependencies without creating that infinite loop.

Any advice or pointers to other references would be much appreciated.

2

There are 2 best solutions below

4
On

The hack to this is to use dropRepeats doing deep comparison.

The answer from gitter that points to "optimized" solution:

function model(input$, db$) {
  return xs.merge(xs.never(), db$.take(1)).map(name => {
    return input$.startWith(name).map(name => {
      return { id: 1, name }
    })
  }).flatten()
};
0
On

Unfortunately the first answer results in breaking the stream of updates to the database.

In gitter, @janat08 suggested the following changes to the persist function, which did work for me:

function persist(state$) {
  return state$.compose(dropRepeats((x, y) => {
    return x.id === y.id && x.name === y.name;
  })).map(log => {
    return $put('logs', log)
  });
};

Not marking this as the solution yet, so Jan has a chance to edit his solution, or if someone comes up wiht a less hacky solution.