The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. I'm struggling to understand this behavior and would appreciate any help in resolving this problem.

const Booking = () => {

    let [total, setTotal] = useState(0)

    const Ticket = ({ ticket, index }) => {

        let [number, setNumber] = useState(0);

        const handleChange = (e) => {

            const order = {
                eventid: eventid,
                amt: ticket.price * e.target.value,
                type: ticket.type,
                tickets: e.target.value,
                email: userdata.email,
                ticketid: ticket.ticketid,
            }

            orders[index] = order

            //setNumber doesn't seem to work unless setTotal is commented out
            setNumber(Number(e.target.value))
            console.log(number)

            let sum = orders.reduce((accumulator, object) => {
                return accumulator + object.amt;
            }, 0)
            setTotal(sum)

        }
         return (
            <div className="p-5 space-y-5 grid grid-cols-6">

                    <select name="number" onChange={handleChange} value={number}>
                        <option value={0}>0</option>
                        <option value={1}>1</option>
                        <option value={2}>2</option>
                        <option value={3}>3</option>
                        <option value={4}>4</option>
                        <option value={5}>5</option>
                        <option value={6}>6</option>
                        <option value={7}>7</option>
                        <option value={8}>8</option>
                        <option value={9}>9</option>
                        <option value={10}>10</option>

                    </select>
                </div>

        )
}

I've attempted to pass the setTotal function as a parameter to the child component but it hasn't resolved the issue

Answer №1

If you encounter this issue, consider utilizing the useEffect hook. Due to the asynchronous behavior of useStrict, calling setNumber(Number(e.target.value)) may not immediately update the state. When you check the value of number using console.log(number) right after setNumber, it will display the previous value rather than the updated one. By omitting setTotal(sum), the functionality seems to function properly as you are not relying on the real-time value of number. Implement a useEffect like so:

const Ticket = ({ ticket, index }: any) => {
    let [number, setNumber] = useState(0);

    useEffect(() => {
        console.log(number);

        let sum = orders.reduce((accumulator: number, object: any) => {
            return accumulator + object.amt;
        }, 0);
        setTotal(sum);
    }, [number, setTotal, orders]); // Ensure all dependencies are included

    const handleChange = (e: any) => {
        const updatedNumber = Number(e.target.value);

        const order = {
            eventid: eventid,
            amt: ticket.price * updatedNumber,
            type: ticket.type,
            tickets: updatedNumber,
            email: userdata!.email,
            ticketid: ticket.ticketid,
        }

        orders[index] = order;

        setNumber(updatedNumber);
    }

    // Your component logic here

    return (
        // JSX content for your component
    );
};

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 checkbox is currently selected, however, I would like it to be dese

I am facing an issue where I cannot figure out why the password checkbox always turns to checked even when it is supposed to stay unchecked. No matter what, it doesn't behave as I intended and I am struggling to explain this behavior... <template&g ...

issue with visibility of checkbox in material ui table row

In a separate file called TradesTable.js, I have created a table using Material UI for my React app. const DummyTableRow = (props) => { let myRows = props.trades.map((trade, index) => { return <TableRow> <TableRowColumn ...

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

Retrieve an enumeration from a value within an enumeration

In my coding project, I have an enum called Animals and I've been working on a function that should return the value as an enum if it is valid. enum Animals { WOLF = 'wolf', BADGER = 'badger', CAT = 'cat', } cons ...

Developing a custom package containing personally crafted type definitions and importing them into the project

I'm in need of creating a private npm package specifically for custom type definitions (typedefs) that are hand-written d.ts files not generated by TypeScript. Since these are proprietary, they cannot be added to DefinitelyTyped. The folder structure ...

Customizing the appearance of the Material UI MuiClockPicker with unique style

I am wondering how I can override the styles for MuiClockPicker? I discovered that using createTheme to override the styles actually works for me, but I encountered an error from TypeScript: TS2322: Type '{ MuiOutlinedInput: { styleOverrides: { roo ...

Should you consider using the Singleton pattern in Node.js applications?

After stumbling upon this specific piece discussing the creation of a singleton in Node.js, it got me thinking. The require functionality according to the official documentation states that: Modules are cached after the first time they are loaded. Multi ...

Customizing the output format of Ng Date Picker beyond the standard ISO-8601

Just to clarify, I'm talking about a specific DatePicker component that can be found at the following link: Although the DatePicker interface is user-friendly and visually appealing, I'm facing an issue with the way it outputs values. While ther ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Angular's use of ES6 generator functions allows for easier management of

Recently, I have integrated generators into my Angular project. Here is how I have implemented it so far: function loadPosts(skip) { return $rootScope.spawn(function *() { try { let promise = yield User.findAll(); $time ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

Tips on serializing two arrays into JSON format and incorporating them in an AJAX request

I have a task where I need to retrieve all the names and details associated with a specific reference number. To accomplish this, I am using a while loop. However, I am unsure of how to encode these values in JSON format so that I can use them in AJAX for ...

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

Enhance the appearance of CodeMirror substrings by applying bold formatting without altering

I am currently utilizing codemirror with primefaces extensions in XML Mode. I need to modify the font style of a specific substring to make it bold. For instance, <User> <Name>Micheal</Name> <Age>25</Age> <Addr ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

Generate a fresh array by filtering objects based on their unique IDs using Angular/Typescript

Hey there, I am receiving responses from 2 different API calls. Initially, I make a call to the first API and get the following response: The first response retrieved from the initial API call is as follows: dataName = [ { "id": "1", ...

Can someone please explain how I can implement a multi-submenu feature using JavaScript?

HTML CODES: <header> <nav> <ul> <li class="asmenu"><a href="#">Menu1 <i class="fa fa-caret-down"></i></a> <ul class="submenu deact ...

Error in Dimplejs: Line is not visible when series is empty

I have a dimplejs.org line chart set up. I am trying to colorize the Clicks data points from blue to red (blue for fewer clicks and a gradient from blue to red for more clicks). When I set the series as shown below, it works fine but the tooltip only incl ...

Minimize data once more using various key criteria

In my current setup, I have created a view that counts reports for different cities. function (doc) { if(doc.type == "report") { emit(doc.city_name, null); } } Using the _count reduce function, I get the following values: {'key': &a ...

What is the best method for transmitting multipart data video files from a NextJS frontend to an Express backend?

I have been struggling to enable users to upload video files and send them through my NextJS API to my Express backend for storage in an S3 bucket. Despite days of research, I can't seem to figure out a solution. I am aware that NextJS has limitations ...