I encountered a problem with iteration where the results appeared perfectly fine, but upon rendering at the component level, the same field loaded with the last object instead

I am facing an issue with rendering the component level when it loads. After clicking on edit and calling the edit function, the data is properly loaded in console and all objects are shown. However, they do not render on the page level.

Below is the code snippet:

const handleEdit = async () => {
    const { searchBrand } = await searchBrandAPI({ id });
    searchBrand[0].translations.forEach(arrVal => {
        console.log(arrVal, 'arrVal');
        setDynamicValues([ ...dynamicValues, {
                transLanguage: { label: arrVal.language, value: arrVal.languauge },
                transName: arrVal.name,
                transIsActive: { label: formatFirstCharUpperCase(arrVal.isActive, String), value: arrVal.isActive },
        }]);
    }); 
    const strIsActive = { label: formatFirstCharUpperCase(searchBrand[0].isActive, String), value: searchBrand[0].isActive }
    setValues({ name: searchBrand[0].name, isActive: strIsActive })
}

Answer №1

This is how I managed to resolve the issue.

const handleEdit = async () => {
    const { searchBrand } = await searchBrandAPI({ id });
    const transData = [];
    searchBrand[0].translations.forEach(arrVal => {
        transData.push({
            transLanguage: { label: arrVal.language, value: arrVal.languauge },
            transName: arrVal.name,
            transIsActive: { label: formatFirstCharUpperCase(arrVal.isActive, String), value: arrVal.isActive },
        });
    });
    setDynamicValues(transData);
    const strIsActive = { label: formatFirstCharUpperCase(searchBrand[0].isActive, String), value: searchBrand[0].isActive }
    setValues({ name: searchBrand[0].name, isActive: strIsActive })
}

I am questioning whether this approach is correct. I attempted using memo and callback but encountered the same issue where only the last record was being displayed despite console logs showing the data correctly! Can anyone confirm if this solution is appropriate or suggest a more efficient method?

Answer №2

To ensure that you are always getting the most up-to-date value of the state, it is important to utilize the useState callback function for accessing the previous value.

const handleEdit = async () => {
  const { searchBrand } = await searchBrandAPI({ id });
  searchBrand[0].translations.forEach(arrVal => {
    console.log(arrVal, 'arrVal');
    setDynamicValues(prev => [ ...prev, {
      transLanguage: {
        label: arrVal.language,
        value: arrVal.languauge
      },
      transName: arrVal.name,
      transIsActive: {
        label: formatFirstCharUpperCase(arrVal.isActive, String),
        value: arrVal.isActive
      },
    }]);
  }); 
  const strIsActive = {
    label: formatFirstCharUpperCase(searchBrand[0].isActive, String),
    value: searchBrand[0].isActive
  }
  setValues({ name: searchBrand[0].name, isActive: strIsActive })
}

Since setState operates asynchronously, the value of dynamicValues may not update immediately after calling setDynamicValues.

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 Material-ui paper component fails to display on the screen

The material-ui paper component is implemented on my homepage and functioning correctly. However, when navigating to another page and returning to the homepage, the paper component disappears, leaving only text rendered. Can you help me identify the issue? ...

Showing commute time using Google Maps API v3

Is there a way to display the travel time immediately when opening Google Maps API v3? If you want to show the driving time as soon as the map is loaded, check out this example that demonstrates switching between travel modes. While it's easy to set ...

Traversing through pair of arrays simultaneously using forEach loop in JavaScript

I am trying to create a for loop that simultaneously iterates through two variables. One is an array named n, and the other, j, ranges from 0 to 16. var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; ...

Functions for abbreviating and combining strings in Javascript

Looking for help to simplify and shorten a Javascript function: $scope.doRefresh = function (){ if($scope.bulletpointPopular){ ArticleService.popular().then(function(data){ $scope.articles = data; }) .finally(function() { ...

Automatically Access a JS/CSS File in the Developer Tools 'Sources' Section

I am aware that I can customize my own Panel in the Chrome Developer Tools, but I am curious if there is a way to click a button within my panel and have the Developer Tools open a particular script or stylesheet in the 'Sources' panel related to ...

Learn the process of assigning the present date using the jQuery UI date picker tool

I am looking to implement the feature of setting the current date using Angular/Jquery UI date picker. I have created a directive specifically for this purpose which is shown below: app.directive('basicpicker', function() { return { rest ...

jQuery alert: A TypeError was caught stating that the object being referred to does not have the 'dialog' method available

For a few days now, I have been tirelessly searching for a solution to this issue and it has caused me quite a bit of stress. My problem lies in echoing a JQuery popup script within php: echo '<link rel="stylesheet" href="http://code.jquery.c ...

How can you access the input value from load dash's debounce function in a Vue.js application?

Is there a way to capture the input entered during the @typing event of the b-autocomplete component in Buefy? During the @typing event, the debounce method is called with specific parameters as shown below- <b-field label="Location"> ...

Introducing unnecessary DOM elements when displaying flash messages

When a user saves in my Rails application, it triggers an Ajax request to save the post and then runs the update.js.erb file. This file contains some jQuery code: $('body').append('<div class="message">Saved</div>'); Due t ...

Changing true/false values to Yes or No in Angular array output

I am working with an array that is structured as follows: { "Tasks": [ { "TaskID": 303691, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { ...

Layer added to map by Mapbox encountered an error during the process

I encountered an error that looks like this: https://i.sstatic.net/TI4HO.png When running the following code snippet: map.on('load', function () { map.addLayer({'type': 'scattermapbox', &ap ...

React router, pay attention to incoming push requests

Currently, I am developing a website that incorporates framer motion and next.js. However, I am encountering a problem where I need to eliminate a class that triggers animations before the path changes. Initially, I attempted: import {useRouter} from &ap ...

A more effective way to obtain exclusive information through Next.js

Whenever a user accesses a specific page (e.g. /post/1), I aim to retrieve the data related to post 1. To achieve this, I extract the URL pathname using window.location.pathname (such as /post/1), eliminate the initial characters (/post/) using substring, ...

Concurrent Icons on Angular-Chart's Piechart

I recently incorporated angular-charts into my project to make the display of charts easier. Initially, setting up and rendering a pie chart was a breeze following the guidelines I found here. Here's a snippet of the code I used: <canvas id="pie" ...

Why is my React Native TouchableOpacity onPress function not functioning properly?

Embarking on my journey with React Native (or any JS framework for that matter), I decided to delve into creating a simple tap game. The concept is straightforward: tap on the blue square, watch it randomly relocate, and repeat the process. Here is a snipp ...

The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet: request(..., function (error, response, body) ...

Preventing scrolling in one div while focusing on another div

I am currently in the process of creating a website that functions as a single page site. The main feature of the site is a masonry grid of images. When a user clicks on an item, a detailed panel slides in from the left. Once the panel is closed, it slide ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

When transitioning the Next application to Typescript, errors are displayed with JSX, but it functions correctly in the browser

After migrating my Next App from JS to TSX, I noticed that the JSX in my TSX file is showing errors and underlined, even though the app runs fine in the browser. I'm puzzled as to why this inconsistency exists. Can anyone provide assistance in resolvi ...