What is the best way to access values from dynamically added components in Svelte when using data from a REST API in a loop?

Previously, I posted this query but now I've made changes to utilize a REST service for retrieving the item list. Everything functions as expected when the data is hardcoded, however, I encounter undefined values when using data from the REST service.

Counter.svelte

<script>
    export let amount = 0;
    function increment() {
        amount += 1;
    }

    function decrement() {
        if (amount > 0) {
            amount -= 1;
        }
    }
</script>


<button on:click={decrement}>-</button>{amount}<button on:click={increment}>+</button>

Updated app.svelte to incorporate rest service in component creation

App.svelte

<script>
... import stuff

    let items;

    onMount( async() => {getItems()});
    function getItemsFromDB() {
      const getItems = (async() => {
        'MY_REST_API",
        {method:'GET'}
      });
      const data = await response.json();
      items=data;
    }
/*
items contains this:
    [{
        id: 1,
        name: 'potato',
        price: 5
    }, {
        id: 2,
        name: 'garlic',
        price: 3
    }, {
        id: 3,
        name: 'rice',
        price: 10
    }];
*/

    function purchase() {
        const itemsWithAmount = items.filter(i => i.amount !== 0)
        console.log(itemsWithAmount)
    }
</script>

<ul>
    {#each items as item}
    <li>
        {item.name} <Counter bind:amount={item.amount}/> <-- **UNDEFINED in page**
    </li>
    {/each}
</ul>

<button on:click={purchase}>Purchase</button>


The counter value turns out to be undefined once the page loads

Expected JSON:

    [{
      id: 1,
      name: potato,
      price: 5,
      amount: 30
    },{
      id: 3,
      name: rice,
      price: 10,
      amount: 400
    }];

Answer №1

Within the given sample code, there are numerous issues that could be addressed. In this response, I will focus on the topic of asynchronous code, a common source of the undefined error.

The issue lies in the fact that the {#each} block is being rendered before the component has been fully mounted and prior to receiving a response from the API.

To tackle this problem, one effective approach is incorporating {#await} when dealing with promises.

<script>
async function fetchItems() {
  const responseData = await apiCall()
  return await responseData.json();
}
</script>

{#await fetchItems() then items}
  <ul>
    {#each items as item}
      <li>
        {item.name} <Counter bind:amount={item.amount}/>
      </li>
    {/each}
  </ul>

  <button on:click={() => makePurchase(items)}>Purchase</button>
{/await}

One drawback of this method is that the 'items' array is not directly accessible within the <script> block.

Alternatively, you can initialize an empty array by using let items; or let items = [];. By doing so, the initial render will display an empty array until it gets updated with new data.

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

The ngx-treeview is displaying an inaccurate tree structure. Can you pinpoint where the issue lies?

I have structured my JSON data following the format used in ngx-treeview. Here is the JSON file I am working with: [ { "internalDisabled": false, "internalChecked": false, "internalCollapsed": false, "text": "JOURNEY", "value": 1 } ...

Capture individual frames from angular video footage

Trying to extract frames from a video using Angular has been quite challenging for me. While browsing through Stack Overflow, I came across this helpful post here. I attempted to implement the first solution suggested in the post, but unfortunately, I was ...

Nestjs RabbitMq Microservices

I'm currently developing a microservice that is responsible for receiving messages from RabbitMQ. However, I am encountering an error message as follows: ERROR [Server] There is no matching event handler defined in the remote service. Event pattern: u ...

The path referenced in typings is incorrect

I am currently facing an issue with my Typescript library that I am trying to publish on npmjs. It seems like the types file is not being exported correctly. The library has a simple method in the src/index.ts file and typings from src/typings/index.d.ts. ...

Exploring alternative methods for accessing object values in TypeScript using a string object path without relying on the eval function

If we have an object in JS/typescript structured like this: var obj = { a: { b:{ c:1 } } } And a string "b.c" is given, how can we evaluate this using only the variables provided and retrieve the value 1 from the object without rel ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

Exporting from Excel is causing dates and times to be displayed as numbers instead

Having trouble with a specific date while exporting an Excel file. Refer to the screenshot of the Excel file for clarity: https://i.stack.imgur.com/7mFE4.png The date '01/02/2019 00:00:00' is being treated as a number instead of displaying corre ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

Tips for activating scrolling on a background element even with a modal window currently displayed

Encountering an issue with Angular and Material for Angular - my application contains multiple modals that disable background scrolling when opened. However, there is one notification modal that should not block the background scroll. Despite not having a ...

Dynamically incorporate new methods into a class

Currently, I am in the process of implementing setters and getters for items that will be stored in session storage. These methods are being written within a service. However, upon attempting to call these functions in my component, I am encountering a tra ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

Struggling to create a functioning toggle button using jQuery in a React application

I've encountered an issue with my react web application. I'm trying to implement a voting system where clicking the like button changes its color and functionality, allowing it to be liked only once. If clicked again, it should return to a neutra ...

The HttpInterceptor is programmed to identify and capture 401 error responses

After successfully implementing a code that called a logout() method upon receiving a 401 response from the server, I encountered issues following an upgrade of Angular from 5.2 to 7.0.3. It seems like either the HttpInterceptor interface has been modified ...

Utilizing the power of d3.js within Angular 4

Currently, I have successfully implemented code to draw a polygon using the mouse in a normal JavaScript file. Now, I am looking to replicate the same functionality in my TypeScript file. Below is an excerpt from my d3.js file: //D3.JS VERSION 3 //------ ...

Tips for efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

Difficulty in connecting React to Node.js with the use of axios

Recently, I embarked on a project using React and Node to create an app that allows users to add people data to a database. The frontend is built with React and can be accessed at localhost:3000, while the backend, developed with Node, runs on localhost:33 ...

The onSubmit function in Formik fails to execute if there are no input values present

I am currently working on building a form using Next.js, TypeScript, and the Formik + Yup libraries. I've encountered two scenarios: one where an input field is visible and Formik captures the value, and another where the input is not visible and the ...

Implement an interface with a specific number of properties in TypeScript

I am attempting to create a custom type that defines an object with a specific number of key-value pairs, where both the key and value are required to be numbers. Here is what I envision: type MatchResult = { [key: number]: number; [key: number]: numbe ...

Is it possible to manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...