What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks.

Everything is functioning smoothly except for the update function. Instead of updating the task at the specific index I select, it only updates the last item in the array.

Here is how my JSX looks:

 const JsxElement = task.map((eachTask, index) => {
    return (
        <Fragment key={index}>
            <div key={index} className="table-data-container">
                <div className="item-data">{eachTask}</div>
                <div className="item-data">{date}</div>
                <div className="item-data">
                    <div className="btn-data-container">
                        <div className="btn-data">
                            <div className="btn" onClick={() => deleteTask(index)}>Delete</div>
                        </div>
                        <div className="btn-data">
                            <div className="btn" onClick={() => UpdateTaskBtn(eachTask, index)}>Update</div>
                        </div>
                    </div>
                </div>
            </div>
            <br/>
            {task.length - 1 === index &&
                <div className="input-update-container">
                    <div className="input-area">
                        <input
                            ref={inputRef}
                            type="text"
                        />
                    </div>
                    <div className="btn-update-add-container">
                        {update ?
                            <div className="btn-add" onClick={() => handleTaskUpdate(eachTask, index)}>Update
                                Task</div>
                            :
                            <div className="btn-add" onClick={handleTask}>Add Task</div>
                        }
                    </div>
                </div>
            }
        </Fragment>

    )
})

The first update button function readies the input, determines the task to be updated, and reveals the update button. The second function is where I intend for the actual update to occur upon clicking.

function UpdateTaskBtn(eachTask) {
    inputRef.current.value = eachTask
    setUpdate(true)
}
function handleTaskUpdate(e, index) {
    const list = [...task]
    list[index] = inputRef.current.value
    setTask(list)


    inputRef.current.value = ""
    setUpdate(false)
}

I aim to have the ability to specify the task at a particular index for updating.

Answer №1

based on this section of code

 {task.length - 1 === index &&

the purpose is to verify if the index represents the final item in the list, and then pass that index to the handleTaskUpdate function. To achieve this, you can initialize an updateIndex state variable

const [updateIndex,setUpdateIndex] = useState()

subsequently, your functions should appear as follows

function UpdateTaskBtn(eachTask,index) {
    inputRef.current.value = eachTask
    setUpdateIndex(index)
    setUpdate(true)
}
function handleTaskUpdate(e, index) {
    const list = [...task]
    list[updateIndex] = inputRef.current.value
    setTask(list)


    inputRef.current.value = ""
    setUpdate(false)
}

remember to include the index when calling the UpdateTaskBtn function within the onClick event

Answer №2

Give this a shot

function processTaskChange(event, taskIndex) {
    const userInput = inputReference.current.value;
    const updatedTaskList = tasks.map((item, i) => i === taskIndex ? userInput : item);
    setTasks(updatedTaskList);

    inputReference.current.value = "";
    setUpdateFlag(false);
}

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

Wordpress multisite facing API CORS problem due to header settings within theme version 5

I am encountering an issue with my React app that interacts with a Wordpress v5 API. const api = `${WAPI}`; const headers = { 'Content-Type': 'application/json' } ; fetch(api, { headers: headers }) .then(function(data){ console ...

Encountering overload error with Vue 3 and Axios integration

Currently utilizing Vue 3, Vite, Axios, and TypeScript. While my function functions properly in development, it throws an error in my IDE and during the build process. get count() { axios({ method: "get", url: "/info/count", h ...

Switch between two distinct menus (Reactjs + Material UI)

Recently, I designed a robust menu system that includes a Switcher feature. The concept is straightforward - if the switch is turned off, display the 1st menu; and if it's on, show the second menu. However, there seems to be an issue. When the switch ...

Limiting zero is ineffective when it comes to pop-up issues

Hey there, I'm looking to prevent users from inputting zero and dot in a specific field, which is currently working fine. However, when the field is within a pop-up, the code below doesn't seem to work. <script> $('#name').keyp ...

How to utilize jQuery to replace the first occurrence of a specific

Suppose I have an array structured like this: var acronyms = {<br> 'NAS': 'Nunc ac sagittis',<br> 'MTCP': 'Morbi tempor congue porta'<br> }; My goal is to locate the first occurrence ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

I am facing difficulties implementing the delete functionality in my express and react application

I'm currently working on a web project application that enables users to display, add, edit, and delete various web projects they have set up, including three premade projects. Everything is functioning properly except for the delete function. I' ...

The useRef() hook call in NextJs is deemed invalid

I have been attempting to implement the useRef() hook within a function component in my NextJs project, but I keep encountering the error below. Despite reviewing the React Hook guidelines, I am unable to determine why this error persists and the functio ...

Why is this <div> element refusing to budge according to my jQuery commands?

Currently embarking on a jQuery coding challenge where I am attempting to maneuver a circle around the page in a square pattern. Numerous methods have been tested with no success thus far. While I would like to showcase my various attempts, it would prove ...

Understanding Express JS's handling of boolean values when reading them as strings

Using axios for communication between my React app and express API has presented an unexpected issue. Before sending the data, the value is identified as a boolean (as intended), but upon receival in the API, it gets converted to and stored as a string. T ...

How to access a variable from within a Phonegap DB function and return it outside of the

I'm struggling with a phonegap db JavaScript script that isn't returning the final string variable "feeds" outside the function. It's currently showing as "undefined". I need help making the necessary changes to properly return the "feeds" v ...

Making sure to detect page refresh or closure using jQuery or JavaScript

Could there be a way to determine if a page has been refreshed or closed using jQuery or javascript? The current scenario involves having certain database values that need to be deleted if the user either refreshes or leaves the page. AJAX calls are bein ...

What could be the reason for useAsync not being triggered upon a state change?

Currently, I am facing an issue where my API call using `useAsync` from the `react-use` library only works the first time. When the state changes, the `useAsync` function does not execute again. export const MyComponent = () => { const [appTaskList, s ...

The upcoming tick override feature will execute the specified function

I am looking to replace the code below The function will run in the following tick req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 5); } : function (fn) { fn(); }; with this new code, window.require.nextT ...

Utilize Material-UI function by passing a function as an argument

I am currently using material UI in conjunction with React. I have a main component: import React, { Component } from 'react'; import CreateNewGarden from './CreateNewGarden'; const cookies = new Cookies(); class Dashboard extends Co ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Elevating state and retrieving data from a dynamically generated text input field

Within my Component, I am initiating a Modal where I pass a form in the following manner:- <Modal show={showGroupModal} onCancel={closeGroupModalHandler} header="Please add Group Name" contentClass="player-admin__modal-content&quo ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Tips for eliminating unnecessary or duplicate dependencies in package.json files

While I am aware that this question has been asked previously on Stack Overflow, I have found that depcheck does not work effectively for me. It provides numerous false alerts and requires specific configuration for libraries like babel, eslint, etc. How ...

Is it possible to trigger useEffect using an onClick event?

const example = () => { useEffect(() => { setState("example") }, [exampleDependency]) } <button onClick={() => Example()}>click me</button> Hey everyone, I'm attempting to execute this function, but I'm ...