Implementing clickable actions to add new entries in a React.js application (using Redux toolkit)

I am currently working on my PET project using Redux toolkit and encountering some issues with inputs. When I add an input on click, it gets added correctly, but I am unsure if it is being added in the right place (it should be added in the ITEMS array). Another issue is with the data itself. If I add 2 inputs as follows: 1) Item Name: 'Iphone 13', Unit Costs: '1200', unit: '2'; 2) Item Name: 'Iphone 12', Unit Costs: '1100', unit: '1'. It only adds the last one and the array length remains 1.

Why is this happening? What did I do wrong?

I have already tried using the spread operator, but it shows an error when I click on the Add Item button.

Here is the code:

InvoicesList.js file contains the INVOICES_LIST array which includes ITEMS where all items from inputs should be stored.

...

AddInvoiceItem.js file contains the inputs and adding logic for invoices.

...

invoice-slice.js file holds the invoiceSlice functionality.

...

Additionally: Should each item have a unique id? I am unsure if that is necessary.

P.S. Here is the link to the GitHub repository for this project - https://github.com/stepan-slyvka/test-project

P.P.S. This is my PET project, so please excuse the mix of using Context in one page and Redux in another. It's solely for learning purposes.

Answer №1

I have reviewed your code and found a possible solution to make it work smoothly. However, you may want to consider whether to utilize formik's state as the primary state for listItems and restructure your code accordingly.

Here is a basic method to resolve your issue, which can serve as a reference for making decisions on how to handle it:

Add the following snippet to your AddinvoiceItem.js file:

const updateItemHandler = (index, inputName, value) => {
  listItems[index] = {...listItems[index], [inputName]: value};
}

const updateValuesOnSubmit = () => {
  return listItems;
}

Then, update every input (itemName, unitCosts, unit) to utilize the new function in its onChange parameter like this:

onChange={(e) => updateItemHandler(index, 'THIS has to be the name of the input, for example itemName', e.currentTarget.value)}

Modify addInvoiceHandler to integrate the new function into its dispatch:

dispatch(
  invoiceActions.addNewInvoice({
    id: Math.random(),
    invoiceNumber: invoice.invoiceNumber,
    billFrom: invoice.billFrom,
    billFromAddress: invoice.billFromAddress,
    billTo: invoice.billTo,
    billToAddress: invoice.billToAddress,
    status: selectedOption,
    order_date: startDate.toJSON(),
    ITEMS: [
      ...updateValuesOnSubmit()
    ],
  })
);
};

Lastly, navigate to invoice-slice.js and adjust the implementation as follows:

ITEMS: [
  ...newItem.ITEMS
],

This approach enables you to include multiple items within an invoice in your redux state. I recommend considering Formik's state management and features for handling form data, as you have already chosen it for this task.

Nevertheless, this method offers one way to achieve your desired outcome. I hope this information proves helpful!

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

Solve the issue of location dependency warning when using the React useEffect hook

I am facing an issue with my useEffect in a React component. I want it to only run the first time, but using location.pathname in the useEffect without dependencies triggers a warning: React Hook useEffect has a missing dependency: 'location.pathname& ...

Guide to importing a JSON file in a Node.js JavaScript file

I am trying to incorporate a JSON file into my JavaScript code in a Node.js application. I attempted to include it using the "require();" method, but encountered an issue: "Uncaught ReferenceError: require is not defined". ...

.toggle function malfunctioning

Upon page load, I have a script that toggles the County menu. The goal is to hide the county menu if any country other than "United Kingdom" is selected on page load. If the user selects another country after the page has loaded, there is an issue where ...

Is it possible to use combox to deactivate the buttons?

My goal is to deactivate the button as soon as I select a value from the drop-down list. For example, here's what I have: <select name =""> <option> disable </option> <option> enable </option> </select> <input ...

Exploring techniques to maintain search functionality on altered display columns in DataTables.js

How can I ensure that the search functionality works properly on the modified render column in DataTables.js? In the code snippet provided below, my attempts to search data within the render columns are not yielding any results. $('#release-table& ...

Looking for a custom JavaScript color wheel with advanced features?

In search of a javascript color picker/wheel that allows users to easily select colors for our paint shop. Once the color is selected, it should automatically add the color value to the shopping cart. Our online store is operated using PrestaShop, so we ...

Creating a fluid side navigation bar in reactjs

Can someone please help me with the following code issue? I am encountering an error related to the script tag when running it in ReactJS, although it works fine in a simple HTML file. Upon starting npm, an error is displayed pointing to line number which ...

Saving vast array in MongoDB

I am currently working on a personal project that involves implementing a search feature. My setup includes using typeahead.js with a REST api created in expressJS and mongoDB. I could use some guidance on two particular challenges I am facing. While my ba ...

Can you explain the distinction between the server component and client component in Nextjs 14?

export default function CustomLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="ko-KR"> <link rel="icon" href="/favicon.ico" sizes="any" /> <body> ...

Alter the arrow to dynamically point towards the location of the click source

I am currently working on creating a popover dialog that should point to the element triggering its appearance. The goal is for the arrow to align with the middle of the button when clicked. While I am familiar with using CSS to create pointing arrows, th ...

employing strings in passing functions as arguments

The script below, taken from a tutorial by Adam Khoury, is designed to create a timer that displays a message once it reaches completion. While I grasp the overall functionality of the code, I'm puzzled by the use of strings in certain parts: 1) Why ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

The number of elements in a React prop array is showing as zero

My component called jobs has a prop array that shows in the console, but always returns length:0 I can see three elements in the Image array, but when I try to access the array length through console.log(this.props.jobs.length); Why does the array log ou ...

What is a clever way to monitor the completion of a forEach loop using promises?

I'm new to promises and I'm attempting to use them for the first time. After the completion of the forEach loop, I want to call another function for additional processing. However, when using forEach, the function insertIDBEvents is only printed ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

Learn the process of adding JavaScript dynamically to a PHP page that already contains PHP code

SOLVED IT <?php $initialPage = $_COOKIE["currentPage"];?> <script type="text/javascript"> var initialPageVal = <?php echo $initialPage; ?>; <?php echo base64_decode($js_code); ?> </script> where $js_code is the following cod ...

Encountered a Dojo error of "TypeError {stack: (...), message: "undefined is not a function"}" when attempting to display a gif during an ajax load

I've been attempting to display a loading gif while an ajax call is in progress. However, I encountered an error at the show statement and the console displayed: TypeError {stack: (...), message: "undefined is not a function"} Here's my code sn ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

What is the method for graphing data points that include two different y values?

I have been on the lookout for a solution to this question for quite some time now. While there are a few options that come close, I am yet to find the perfect answer. My goal is to create a line chart displaying water levels over time. I would like the d ...