Tips for displaying HTML content dynamically in React using TypeScript after setting a stateVariable

To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows:

    const formService = new FormService();
    
    const [appointmentDate, setAppointmentDate] = useState<AppointmentDate>();
    const [formattedDate, setFormattedDate] = useState<string>();
    const [formattedTime, setFormattedTime ] = useState<string>();
    const [formattedTime20MinutesBefore, setFormattedTime20MinutesBefore] = useState<string>();


    useEffect(() => {
        init();
    },[])

    const init = async () => {
        await getAppointmentData();
        await organizeTheDates();
    }

    const getAppointmentData = async () => {
        const appointmentDateVar = await formService.getAppointmentPageInformation(3);
        setAppointmentDate(appointmentDateVar);
    }

    const organizeTheDates = async () =>{
        if (appointmentDate) {
            // set the time and date variables
            const date = new Date(appointmentDate.dateTime);
            setFormattedDate(`${date.getDate().toString().padStart(2, '0')}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getFullYear()}`)
            setFormattedTime(`${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`)

            const twentyMinutesBefore = new Date(date.getTime() - 20 * 60000);
            setFormattedTime20MinutesBefore(`${twentyMinutesBefore.getHours().toString().padStart(2, '0')}:${twentyMinutesBefore.getMinutes().toString().padStart(2, '0')}`);
        }
    }

Now, to render the code after the values are set, I have implemented an if-else block. However, when running the code, it gets stuck at the else page.

if(formattedDate !== undefined && formattedTime !== undefined ){
        return ( ** my page ** ) } 
}else {
        return <div>loading</div>;
    }

Upon saving the code in the IDE again, React re-renders the page and this time it enters the if block, indicating that the issue is due to the asynchronous nature of useState variables. Is there a way to resolve this? Thank you very much.

UPDATE

Following Quentin's answer, I made changes to the code as shown below. Thank you for your assistance.

const init = async () => {

        await organizeTheDates(await getAppointmentData());
    }

    const getAppointmentData = async () => {
        const appointmentDateVar = await formService.getAppointmentPageInformation(3);
        setAppointmentDate(appointmentDateVar)
        return appointmentDateVar;
    }

Answer №1

setAppointmentDate is responsible for storing a value in the state. It doesn't immediately alter appointmentDate, so you cannot retrieve it from there within organizeTheDates.

Instead, consider returning a value from getAppointmentData and then having the init function pass it to organizeTheDates.

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

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Protractor enables horizontal scrolling for a Div element

My struggle to scroll to the right persists despite all attempts I experimented with various solutions, but none seem to work await browser.executeScript('arguments[0].scrollIntoView(true)',element.getWebElement()) The issue still remains unr ...

How can I prevent the enter key from working with Twitter Typeahead?

Is there a way to prevent the enter key from being pressed on an element within Twitter Typeahead's dropdown feature while using Angular with Typescript? I attempted to utilize preventDefault() when event.keycode === 13 on the ng-keydown event for th ...

Dynamic table row that expands to show additional rows sourced from various data sets

Is there a way to expand the table row in an angular-material table when it is clicked, showing multiple sets of rows in the same column as the table? The new rows should share the same column header but not necessarily come from the same data source. Whe ...

The issue arising from utilizing the export class function in Angular 8

Hey there! I'm working on an Angular application and just getting started with it. My current version is Angular 8, and I've encountered an issue that I need help with. In my project, I have a shared model named "Client" which is defined in a fi ...

Using JSON data in an ArrayBuffer with TypeScript

I am currently struggling with converting the received ArrayBuffer data from a server via Websocket into another format. Below is the WebSocket code snippet: let ws = new WebSocket('wss://api.example.com/websocket'); ws.binaryType = 'arrayb ...

When you call Subscribe(), you will receive the output "complete: () => void; 'complete' is defined in this context. What exactly does this signify?

Currently, I am following a tutorial and after meticulously checking and rechecking, I can confidently say that my code matches exactly with the one the professor is using. The tutorial involves creating a simple Single Page Application in Angular using Ty ...

Depend on a mapping function to assign a value to every option within a discriminated union

While utilizing all variations of a discriminated union with conditional if statements in TypeScript, the type is narrowed down to the specific variant. To achieve the same effect by expressing the logic through a mapping from the discriminant to a funct ...

Achieving a delayed refetch in React-Query following a POST请求

Two requests, POST and GET, need to work together. The POST request creates data, and once that data is created, the GET request fetches it to display somewhere. The component imports these hooks: const { mutate: postTrigger } = usePostTrigger(); cons ...

Having trouble using the 'in' operator to search for 'Symbol(StrapiCustomCoreController)' while transitioning Strapi to TypeScript

I'm in the process of converting my strapi project to typescript. I've updated all strapi packages to version 4.15.5 and converted the files to ts extension. However, upon running strapi develop, I encounter the following error: [2024-01-03 10:50 ...

What is the best way to interpret a line break within a string variable in TypeScript?

Realtime Data base contains data with \n to indicate a new paragraph. However, when this data is retrieved and stored in a String variable, the website fails to interpret the \n as a paragraph break: https://i.stack.imgur.com/tKcjf.png This is ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Conditional return type mistakes

I'm facing an issue with a function that takes a parameter "value" and is supposed to return 0 or 1 based on its true or false value. Check it out here. const f = <T extends boolean>(value: T): false extends T ? 0 : 1 => { if (value === ...

NodeJS can be used to convert JSON data into an XLSX file format and allow for

I am currently working on a project in nodejs where I need to convert JSON data into XLSX format and then download it to the client's browser. I have been using the XLSX npm module to successfully convert the JSON data into a Workbook, however, I am f ...

Type of Multiple TypeScript Variables

Within my React component props, I am receiving data of the same type but with different variables. Is there a way to define all the type variables in just one line? interface IcarouselProps { img1: string img2: string img3: string img4: string ...

Modifying the value of an object key with Javascript

The information I am working with is structured as follows: obj = { pref: { language: 'English', } }; My goal is to update the language field to 'Spanish'. ...

React app's compilation is failing due to non-compliant ES5 code generation of the abab module, resulting in errors on IE

Can anyone explain why a create-react-app project using TypeScript and configured to generate ES5 code is not functioning on IE11 due to the "atob" function from the 'abab' package not being compiled into ES5 compliant code? module.exports = { ...

Discover the steps to activate and utilize mat-error without the need for form control manipulation

Have you encountered an issue with using ngModel and mat-error without a form? Is there a workaround that allows the use of mat-error with ngModel? #code <mat-form-field appearance="fill" class="w-48per"> <mat-label>Fi ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...