Adding an object to an ArrayList: A step-by-step guide

I'm encountering issues with adding objects to the list. I have a list of floors, each floor containing rooms. I can successfully add a floor, but I'm unsure how to add rooms to the floor list.

I've attempted to access floor[index] or id, but it doesn't seem to be working. What steps should I take next?

export default class HomeWork extends Component {
    constructor() {
        super();
        this.state = {
            floors: [
                {
                    floorId: 1, name: 'floor1', rooms: [
                        { roomId: 1, name: 'new room' },
                        { roomId: 2, name: 'new room' }]
                },
                {
                    floorId: 2, name: 'floor2', rooms: [
                        { roomId: 1, name: 'new room' },]
                }
            ]
        }
    }
    addRoom(index) {
        const RoomArr = [...this.state.floors[index].rooms]
        RoomArr.push(
            { id: 2, roomName: 'New Room' });
        this.setState({
            // Currently stuck at this point
        })
    }
    render() {
        return (
            <View style={styles.parent}>
                <View >
                    <FlatList
                        data={(this.state.floors)}
                        renderItem={({ item }) => {
                            return (
                                <View>
                                    <View >
                                        <Text>Floor {item.floorNumber}</Text>
                                        <Text>Room per Floor:</Text>
                                        <Text >{item.rooms.length}</Text>
                                        <TouchableOpacity onPress={(index) => { this.addRoom(index) }}>
                                            <Image source={Images.plusIcon}></Image>
                                        </TouchableOpacity>
                                    </View>
                                    <FlatList
                                        data={(item.rooms)}
                                        numColumns={4}
                                        renderItem={({ item }) => {
                                            return (
                                                <View>
                                                    <Text>{item.roomName}</Text>
                                                </View>
                                            )
                                        }}
                                    ></FlatList>
                                </View>
                            )
                        }}
                    ></FlatList>
                </View>
            </View>
        )
    }
}

My hope is to at least be able to retrieve the index of the floor.

Answer №1

To obtain the floor data using the spread operator, modify a specific floor by its index, and then employ setState with the updated floors, follow this approach:

appendRoomToFloor(index) {
    let floors = [...this.state.floors];
    floors[index].rooms.push({ id: 2, roomName: 'New Room' });
    this.setState({ floors })
}

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

Conceal the information within a table using angular js and HTML

Just starting out with angular and I have a table that displays angular data directly in the HTML without any controller or model. <table width="98%" border="0" cellspacing="1" cellpadding="2" class="labels" align="center" id="locc"> <tr style ...

Different ways to generate DOM element using jQuery

When it comes to creating a new DOM element from JavaScript or jQuery code, there are numerous methods to consider. Some examples include: $('<div>').prop('id','someid').addClass('someclass'); $('<div& ...

What sets apart +variable+ and ${variable} in JavaScript?

Just starting to code and eager to learn. While I was taking in a lecture, I came across this interesting snippet of code: var coworkers = ['go', 'hello', 'hi', 'doit']; <script type="text/javascript&q ...

Simply use `$timeout` inside the `$watch` method in AngularJS to create a chained

My goal is to link two $timeout functions inside a $watch. This $watch monitors user actions, and if any action is detected, both $timeout instances are canceled. Below is the code snippet outlining this scenario. .run(['$rootScope', '$loc ...

Incorrect media type linked to Gmail API attachment error

I need help sending a message via the Gmail API in JavaScript, including a JPEG file attachment. My code so far looks like this: $.ajax({ type: "POST", url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart", he ...

Using JQuery to Identify the Clicked Div Container

Currently working on a JQuery script to determine which specific div box was clicked, but running into some issues. I understand that there are other approaches to achieve this by directly invoking functions upon clicking a div box, but I want to first ide ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

Unable to load CSS background image

As I develop a website for a fictional company to enhance my skills in HTML, CSS, and JavaScript, I am encountering an issue with loading my background image. If someone could review my code to identify the problem, I would greatly appreciate it. Check ou ...

Using a lambda function with skimage.measure.block_reduce

In my data analysis project, I start with an array: import numpy as np arr = np.random.randint(0,10,size=[8,8]) The values in arr are: array([[9, 1, 8, 2, 0, 4], [0, 7, 6, 9, 7, 5], [0, 7, 1, 6, 6, 2], [3, 6, 3, 3, 8, 1]]) To reduce ...

Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to r ...

Dealing with CORS, IIS7, and PHP - Overcoming the Access-Control-Allow-Origin obstacle

I am attempting to enable another local host (such as javascript.dev) to make a xhr request to this particular host, which operates on an IIS7 server. When I perform a curl -I command, the headers I receive are as follows: HTTP/1.1 200 OK Content-Length: ...

If IE's conditional comments are dysfunctional

Could this be a silly question? I feel puzzled by it. I've been using an if IE conditional statement to address some issues in IE6. In the head section, this is what I have: <!--[if lt IE 7] > <script type="text/javascript" src="js/ie6.js" ...

capturing the HTML title and storing it in a JavaScript variable

Is there a way to retrieve the title "Some Name" in the JS file and have it be populated by the hyperlink's title attribute, which is set to "sometitle" in the HTML code? JS var randomtext={ titleText:"Some Name",} HTML <a class="css" title="so ...

I would appreciate it if someone could clarify how the rendering process occurs in React in this specific scenario

let visitor = 0; function Mug({name}) { visitor = visitor + 1; console.log(name, visitor); return <h2>Coffee mug for visitor #{visitor}</h2>; } return ( <> <Mug name={"A"}/> <Mug name={"B&qu ...

Scrolling to an id element in Vue.js can be achieved by passing the ID in the URL using the "?" parameter. This

My challenge involves a URL http://localhost:8080/?london that needs to load directly to the element with an id of london in the HTML section <section id="london"> on the page. Using http://localhost:8080/#london is not an option, even though it woul ...

Pause before proceeding to the next iteration in the loop

I am currently facing an issue while trying to send a message through an API using a function. The function returns a value called messageLogId, which I'm attempting to update in the main loop at Attendence. However, when executing the code, the value ...

When positioned at high or low angles, the camera starts acting strangely

In my Three.js scene, I have a camera that I need to move and change its angle around a specific focal point. The focal point is actually the camera's position, and during rendering, I translate the camera by using the cameraBuff vector to position it ...

Can you please explain the purpose of the mysterious JavaScript function f => f?

Currently, I am utilizing a third-party library that utilizes a function with functions as arguments. During my conditional checks, I determine whether to add a particular function as a parameter or not. However, providing null in these cases results in er ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...