Steps for updating the value of a key/value pair in an array using a handleChange function

Managing a dynamic grid with varying numbers of rows and 3-5 cards per row can be complex, especially when using useSelector and .map to populate the data for each card. The initial state includes multiple key/value pairs, some unique to each record. Visualizing this in a console.log may look like:

[ 0: {Key: 1, PerformanceYR: "2019", SubRegionKey: 24, showDetail: false},
  1: {Key: 2, PerformanceYR: "2019", SubRegionKey: 24, showDetail: false},
  2: {Key: 3, PerformanceYR: "2019", SubRegionKey: 24, showDetail: false} ]

The goal is to update the 'showDetail' property from false to true for a specific record when clicking on a button associated with that record's key. However, current implementations are affecting all records rather than just the targeted one. Here is a snippet of the relevant code:

const ServiceAreaTile = () => {
  const psOverviewSA = useSelector((state) => state.psOverviewSA);
  const classes = useStyles();
  const [detail, setDetail] = useState(false);

  const handleChange = (event, data) => {
    let index = psOverviewSA.findIndex(item=> item.Key === event.currentTarget.id)
    let newArray = [...psOverviewSA]
    setDetail(!newArray[index].showDetail)
  }

  return psOverviewSA.map((data) => {
    data.showDetail = detail;
    return (
      // Code for displaying the grid and cards
    )

The issue arises when trying to change 'showDetail' based on the clicked button's id matching a key in the data set. Instead of only affecting that specific record, the current implementation alters all 'showDetails'. Further tweaking needs to be done at the button level:

<Button id={data.Key} onClick={(event, data) => handleChange(event, data)} >
  <ExpandMoreIcon />
 </Button>

To render additional details for records with 'showDetail' set to true, the following code section comes into play:

{data.showDetail && <div><Typography>{data.SubRegionKey}</Typography></div>}

Diving into the complexities of associating the handleClick function with useState versus useSelector reveals nuances that impact the functionality. While immediate solutions seem elusive, perseverance will eventually lead to a breakthrough. Stay patient in the journey towards resolving these challenges!

Answer №1

After some troubleshooting, I discovered that the key was to include "showDetail: false" in the action imported through useSelector instead of adding it directly into my component file. Therefore, I had to modify my action code as shown below (pay close attention to the second-to-last line for the addition of "showDetail"):

import axiosconfig from "../../axiosconfig";
export const getpsOverviewSA = (performanceYR, subRegionKey) => async (
  dispatch
) => {
  const response = await axiosconfig.get("/api/psOverviewSA", {
    params: { performanceYR, subRegionKey },
  });
  dispatch({ type: "GET_PS_OVERVIEW_SA", payload: response.data, showDetail: false });
};

With this adjustment, everything is now functioning perfectly.

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

Verifying Objects with AngularJS JSON

Currently, I am using Angular to import a json file and showcase it in a table. Since some of the objects are different, I want to check if job.text is present. [ { "job": { "href": "www.google.com", "text": "Google" }, "api": " ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...

Even after assigning the class "img-fluid" to my image, it still fails to properly adjust to the screen size

I added the class "img-fluid" to my image in Bootstrap, but it's not fitting on my webpage. What should I do? <img src="images\406201.jpg" class="img-fluid" alt="..."> <div style="margin-top: 0p ...

Effortlessly creating a sine wave effect for a link underline on hover using CSS and jQuery

Here is an example: $(function(){ var x = 0; setInterval(function(){ x-=1; $(".link-wavy:hover").css('background-position', x + 'px 100%'); }, 20); }) body { font-family: 'So ...

PHP is failing to send a JSON response, but no errors are being logged in the PHP error log or displayed in the

Hey there, I'm feeling a bit frustrated and really not a fan of Javascript at all. Can someone please help me figure out why this isn't working? It's frustrating because everything seems fine when I return a simple string instead of trying t ...

The jQuery formvalidator plugin for file validation isn't functioning as expected

I am attempting to validate the file type input using the formvalidator.net plugin, however, I am not seeing any errors. What could be wrong with the code below? It is functioning properly for other types of input. Here is an example of what I am trying: ...

Encountering an issue with a Vercel deployment of a Next.js project due to an unexpected token error: 'export'

Every time I attempt to compile the latest version of my Next.js project, it throws a build error with the following log. Interestingly, when I execute npm run dev and view the project on the local port, everything functions perfectly. Have any insights? ...

How can I click on an item when using pagination?

When using react.js, I am encountering a difficult-to-understand error. My component works fine without pagination - it displays all items and allows you to click on them. Pagination is working properly as well, but the issue arises when trying to click on ...

The TextArea element is experiencing issues with the Jquery function

In my asp.net web application, I have implemented a JQuery function to restrict user input characters. $(document).ready(function () { $('input').on('input', function () { var c = this.selectionStart, ...

JQuery does not have the ability to compare the current date and

I've encountered an issue while comparing two date scripts that resulted in incorrect output. Here is the code that I used: var current = new Date(); var date = new Date($(this).val()); alert(current) == "Sat Aug 23 2014 14:42:00 GMT+0700 (ICT)" aler ...

Modify the web address on a WordPress site

My template contains various titles, all pulled from the database. When I select a specific title, it opens up a second page with a detailed description and a URL link: /category-details/?expertise_category=INSTITUTIONAL However, I would prefer the link ...

Unable to change the NodeJS version

Nodejs installation not updating Nodejs version $ nodejs --version v8.10.0 $ sudo npm install -g nodejs@latest + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c6c7cccdc2dbe89886988698">[email protected]</a> up ...

Text inside the placeholder is not displaying correctly in the React.js user interface

When passing placeholder text as a prop to the <FormField/> component from the <CreatePost/>, I encountered an issue where the placeholder text was not displaying in the form. Interestingly, when I used console.log within the <FormField/> ...

Displaying only the navigation controls of Bootstrap 5 Carousel without the actual content

Currently, I am in the process of building an HTML website and incorporating the bootstrap 5 framework into it. My main objective is to integrate a bootstrap 5 Carousel within a section of the website alongside an image, as demonstrated in the following i ...

A guide to implementing the look-at feature in Ar.js through code

I'm having trouble getting the look-at functionality of Ar.js to work dynamically with JavaScript. The 3D object isn't properly oriented towards the screen for some reason. ...

Generate an automatic "proxy" for ASP.NET MVC Controller to communicate with AngularJs service

Whenever I utilize an ASP.NET MVC controller with AngularJS, the majority of my controller functions consist of JSON results. When creating my AngularJS service, I find myself repeatedly writing similar code to handle GET or POST calls to my ASP.NET contro ...

AngularJS showing up as normal text

I can't seem to get angular JS working properly on my website. It keeps displaying as plain text in the browser and doesn't receive any information from the app2.js. I've double-checked all the dependencies and their locations in my code, so ...

Is it possible to pass an AngularJS ng-form object as a parameter in ng-if?

When I try to preview, the save button in my preview mode remains enabled. You can view the code snippet here: http://plnkr.co/edit/I3n29LHP2Yotiw8vkW0i I believe this issue arises because the form object (testAddForm) is not accessible within the ng-if s ...

Randomly generated numerical value in input field

How can I generate a 15-digit number using JS code and then reduce it to just 5 or 6 digits in a text box? <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript ...