typescript error: referencing a variable before assigning a value to it in function [2454]

I am currently in the process of creating a store using nextJS

I have two variables that are being assigned values from my database through a function

    let size: Size

    let ribbonTable: Ribbon
    
    async function findSizeCategory(): Promise<void> {
    const category = product?.category ;
    switch(category) {
        case "mens":
        size = await db.select().from(mens_size);
        break;
        case "womans":
        size = await db.select().from(womans_size);
        ribbonTable = await db.select().from(ribbon)
        break;
        case "kids":
        size = await db.select().from(kids_size);
        ribbonTable = await db.select().from(ribbon)
        break;
    }
    }
    await findSizeCategory()

However, I encounter a typescript error when trying to use them in the map function and if the length of ribbonTable is greater than 0

        <label className="block">
            What size are you?
            <select>
            {size.map(s =>
                <option key={s.size_id} value={`${s.size_id}`}>{s.size}</option>
            )}
            </select>
        </label>

                {ribbonTable && ribbonTable.length > 0 && (
                    <label className="block ">
                        Select a ribbon:
                        <select>
                            {ribbonTable.map(r =>
                                <option key={r.ribbon_id} value={r.ribbon_id}>{r.ribbon}</option>
                            )}
                        </select>
                    </label>
                )}


Answer №1

Your code snippet is not fully visible, making it a bit challenging to provide accurate advice. However, based on the information available, it seems like you need to initialize the variables with initial values. The function findSizeCategory() is asynchronous, so there is a possibility that the variables will be initialized after the view is rendered.

As a result, using these variables in the template before they are initialized can lead to errors. To resolve this issue, consider setting default values for the variables:

let size: Size = ...; // assign a default value of the 'Size' type
let ribbonTable: Ribbon = ...; // assign a default value of the 'Ribbon' type

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

Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple obj ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

Employing a general-purpose function in a recursive manner

My function that removes properties from an object and returns a new one works fine, but it runs into issues when dealing with nested arrays of objects. How can I tackle this challenge? interface User { id: number; name: string; items?: User[]; } co ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

I am struggling to display the data fetched by Next.js on the page

I am struggling to display the data from the first file in my tanstack table or as a string within the HTML, even though I can see it in a console.log when grabbed by axios. The tanstack table worked fine with hardcoded data. In the console image provided, ...

What is the syntax for declaring a boolean or object type?

Is it possible to create a variable in TypeScript that can hold either true/false or an object of booleans? I'm still learning TS and would like some input on this syntax. variableA: { a: boolean, b: boolean } | boolean I found a workaround for now, ...

Steps for transferring data between two components

I'm looking for a way to transfer an object's id from one component to another. <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef></mat-header-cell> <mat-cell *matCellDef="let user"> ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

How can I pass a service method as a parameter in an Angular 2 component?

Within the component: myFunction(): void { this.myOtherFunctoin(this._myService.serviceMethod); } private myOtherFunction(func : Function){ func(); } Regarding service calls: serviceMethod(){ this.somethingMethod(); // "this" is coming as ...

Encountered an error while defining a Vue component using TypeScript with the @Prop decorator

When working with Vue.js and TypeScript, I usually use the following syntax: @Component({ props: ['uploadUrl'], }) export default class SelectionModal extends Vue { let x = this.uploadUrl // This variable `uploadUrl` is NOT resolve ...

Utilize TypeScript's TupleIndexed type to strictly enforce read-only properties for arrays when they are used as function arguments

Looking to define a TypeScript type that accepts a type parameter T along with a tuple or ReadonlyArray of keyof T, and returns a ReadonlyArray containing the keys indexed into T. type TupleIndexed<T, K extends ReadonlyArray<keyof T>> = { [C ...

How is it that TypeScript still expects a valid return from an overridden method, even when it cannot be reached?

After creating a generic RESTClient with some abstract functions, I encountered an issue where not all REST actions are implemented. In these cases, I wanted to throw an error. The problem arose when trying to override the TypeScript method to both return ...

Challenges with implementing asynchronous functions in NestJS controllers

Currently, I am in the process of developing a finance tracker application that involves importing data from a CSV file. The import functionality checks if an entry already exists in the database, adds a specific category to it if not found, and then saves ...

Building Components on the Fly with Angular 5

I've been utilizing code similar to this to dynamically generate components within my application. These components need to support dynamic inputs. However, upon attempting to upgrade to Angular 5, I've encountered an issue with ReflectiveInjecto ...

Troubleshooting the problem of redirecting a website to www on IIS 10 (Windows Server 2019)

I have a React website running on port 3000. Currently, the website can be accessed with and without the www prefix, causing duplicate SEO issues. I want to ensure that the website always redirects to https://www.pess.org.ua. web.config <?xml version=& ...

Using a single TypeORM connection across various modules in NestJS

In the process of developing a link shortener, I have set up a CRUD REST API for authentication and creating shortened links. Now, I am looking to manage redirects for these shortened URLs without using the same path as my API endpoints (e.g. /api/v1/). Af ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

What is the proper way to implement an if-else statement within objects?

Is there a way to convert the code below into an object structure so I can access nodID and xID keys from different files? The issue lies in the if statement within the code. My idea is to use export const testConfig = {} and import testConfig into any fil ...

Neglect variables that have not been declared (TypeScript)

Currently, I am working on developing a WebExtension using TypeScript that will be later compiled into JavaScript. This extension relies on one of the browser APIs offered by Firefox, specifically the extension API. An example of this is my use of the get ...