Encountering an endless loop when utilizing cycle-idb with a text field for user input

Struggling to develop a basic test app that captures user input from a text field, displays it, and stores it using cycle-idb. Unfortunately, I've been stuck in an endless loop no matter what steps I take.

Below is the complete 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$,
  };
}

Attempting to implement the MVI pattern similar to TodoMVC, however, struggling with managing circular dependencies and avoiding the infinite loop. Any guidance or suggestions on additional resources would be greatly appreciated.

Answer №1

Regrettably, the initial response leads to interrupting the flow of updates to the database.

Over in gitter, @janat08 proposed the following modifications to the persist function, which actually resolved the issue 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)
  });
};

I am not designating this as the final solution just yet, giving Jan a chance to refine his suggestion or if someone comes up with a more elegant fix.

Answer №2

A useful trick is to utilize dropRepeats with deep comparison.

There's a suggestion from gitter that offers an "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()
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered in Babel version 6 with the transform-es2015-classes plugin in loose mode, causing a SyntaxError when using async/await

After updating to the latest version of Babel v6, I encountered an issue with the transform-es2015-classes plugin in loose mode (https://github.com/bkonkle/babel-preset-es2015-loose/blob/master/index.js#L8) causing problems with async/await functions. Here ...

How can I detect if the browser's built-in object is available in Angular?

Exploring the Wechat JS API: The Wechat JS API relies on the WeixinJSBridge object within the Wechat built-in browser. This object is not immediately available upon opening the WebView; the client-side needs to initialize it. Once the WeixinJSBridge object ...

Execute a JavaScript function when a form is submitted

Seeking to reacquaint myself with Javascript, encountering difficulties with this fundamental issue. https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/ var name = document.getElementById("name"); function validate() { alert("Your name is " +name); } < ...

What is the best way to utilize Link navigation in order to navigate away from a blocked route in the latest version of Next.js,

DISCLAIMER: I raised this issue on the Next.js GitHub repository, but it was closed without recognition. The solution provided did not resolve my problem, leading me to seek help here. The Issue at Hand I have created a demo app (accessible here) on Code ...

Delete the value from the array and refresh the HTML with the updated total amount, or display '$' if there is no total amount

Currently, I have two inputs: debit and credit. On button click events, they update an array called 'debits'. Debit adds positive values while credit adds negative values. The next step is to sum the values in the array and assign it to a variab ...

Tips for displaying Facebook comments with JavaScript

Can anyone help me figure out how to customize the data-href for Facebook comments using JavaScript (jQuery)? I tried incorporating the code below, but it's not displaying anything in the div col2. $("#col2").html( id+"<div class='fb-comm ...

Selecting the checkbox will activate the POST endpoint

I am working on a nodejs/express app and looking for a way to update my database using a POST route when a checkbox is clicked. The challenge I am facing is that I want to avoid using a submit button or jQuery. I am currently using a Bootstrap4 checkbox ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

Enhance the jQueryUI progress bar by dynamically updating it with inner HTML data

I am working on implementing a jQueryUI progress bar and facing some challenges. Here is the basic code for the progress bar: <script> $(function() { $("#progressbar").progressbar({ value: 50, }); }); </script& ...

I'm attempting to store this HTML code in local storage in order to utilize it on a new cart page, but I keep encountering an error

Here is the HTML snippet: <div class="cofefe"> <img src="photos/Shop%20-%20French%2Roast.png"> <p>Somecoffee</p> <p>15</p> <p>French ...

Using the append() method in d3 with a function argument adds new

This is functional code: // A d3.select("body").selectAll(".testDiv") .data(["div1", "div2", "div3"]) .enter().append("div") .classed("testDiv", true) .text(function(d) { return d; }); The next snippet is essentially the same, except that ins ...

ng-repeat hide all elements except the first one

Hello there! I'm currently working on rendering a form based on an API call. Using a couple of filters, I am able to hide all elements that have 'id' in the title and which equal 0. However, I do need to display the initial element Id. I tho ...

What are the steps to modify the sign in page on keystone.js?

I recently started using keystone.js and I'm having trouble locating the sign in page within the files. I've searched through all of the keystone.js files but can't seem to find where it's written. Can someone please guide me on how to ...

MYSQL table successfully created, however encountering a 500 error when attempting to post data

I've been working with the Node module KNEX for making MYSQL calls, and I'm trying to allow users to add their own custom tables. I have successfully added a database to MYSQL with all the necessary columns, but unfortunately, I keep encountering ...

Encountering an unexpected token 'Indent' while working with Jade in Eclipse

Currently, I am delving into the world of node, angular, javascript, express, and jade. Transitioning from a purely .net based coding environment has presented me with quite the learning curve. While following a tutorial, I encountered a roadblock at step ...

Including a Pinterest image hover widget following the completion of an Ajax load

I have implemented the Pinterest image hover widget on my website to allow users to easily pin images to their Pinterest accounts. You can find the widget here. (Make sure to click the image hover radio button under button type to see the one I am using.) ...

Utilizing AngularJS to selectively filter objects based on specific fields using the OR operator

My collection includes various items with different attributes. For instance, here is the information for one item: {"id":7,"name":"ItemName","status":"Active","statusFrom":"2016-01-04T00:00:00","development":"Started","devStartedFrom":"2016-01-04T00:00:0 ...

Ways to remove code from production during build process?

Is there a way to omit typescript code from getting bundled by webpack during build process? Let's say I have the following line of code in my app.ts file (a nodejs application): const thisShouldNotBeInProductionBundleJustInDevBundle = 'aaaaaaa ...

Direct AngularJS to automatically reroute users from the login page to the welcome page

I am currently developing a web application where I need to redirect from the login page to the welcome page once the user id and password have been validated. <script> var app = angular.module('myApp', []); app.controller(&apo ...

What is the best way to pinpoint the origin of the element.style being injected by JavaScript?

I've been tasked with updating a client's WordPress website, but I'm still getting acquainted with the overall structure of the site. When looking at the blog page (), I noticed that posts are displayed within a wrapper labeled #blogleft, a ...