Keeping calculated values in the React state can cause issues

In an attempt to develop a component resembling a transferlist, I have simplified the process substantially for this particular issue.

Consider the following example: the react-admin component receives two inputs - a subset of selected items record[source] (where source refers to a property on the record object, specific to react-admin), and a list containing all potential items allItems. The objective is to showcase two lists within the component: one featuring the selected items, and another displaying the items that are NOT selected. The selected items list is provided, while the list of NOT selected items is determined by filtering all items and excluding those already selected.

Despite my efforts, which may be hindered by my limited experience with JavaScript/React, I am encountering difficulties in achieving the desired outcome.

The issue lies in the fact that although theleft variable is functioning correctly and showcasing the selected items, the right variable appears to remain empty, despite confirming that the unselected variable contains the intended list when initializing useState(unselected).

Please note: the items are simply strings, and it is evident that the unselected variable does contain the appropriate items. Hence, the problem seems to be rooted in handling state rather than generating the unselected list.

I believe I may have reached the limits of my understanding regarding React/Redux states. Any guidance or suggestions would be greatly appreciated!

import React, { useState } from 'react';

export const TransferList = ({record, source, allItems}) => {

  var unselected = allItems.filter(name => !(record[source].includes(name)));
  const [left, setLeft] = useState(record[source]);
  const [right, setRight] = useState(unselected);

  return (
    <div>
      Selected:
      <ul>
        { left.map(s => <li>{s}</li>) }
      </ul>
      Unselected:
      <ul>
        { right.map(s => <li>{s}</li>) }
      </ul>
    </div>
  );
}

Answer №1

When the allItems array is updated, you can use useEffect to track these changes and update the selected items:

useEffect(()=>{
  const selected = allItems.filter(item => record[source].includes(item));
  setSelectedItems(selected);
},[allItems])

Test this code to confirm if it functions correctly.

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

"Utilize React Spring's useTransition feature to effectively modify state updates within exiting

I'm currently utilizing react-spring to implement transitions within a list of text elements. The animation I have set up is shown in this gif: https://i.stack.imgur.com/pIbTx.gif However, there seems to be an issue where the text in the component th ...

Create an interface property that can accommodate various disparate types

In a React component, I am looking to use an external type (from react-hook-form) that can accommodate 3 specific types representing an object with form values. I initially thought about using a union type for this purpose, but encountered issues when pas ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

Creating a new array in Vue.js by filtering the results of a promise iteration

Is there a way to use the splice method to insert promise values from an old array into a new one for vue reactivity? I'm encountering an issue where the newArray remains empty and does not receive any values. Check out this link for more information. ...

Load ajax content dynamically based on the updated URL

Exploring ajax for the first time and having some issues. Currently, I am retrieving text from files based on the URL. This is how it's set up: var home_url = "blahblah/index.html#home"; var test_url = "blahblah/index.html#test"; $(document).on("c ...

Retrieve the encrypted URL

I'm facing an issue with extracting parameters from an encrypted URL. When using the queryparams function, it only retrieves a portion of the URL after being decrypted. For instance, consider this example URL: http://localhost:4200/househouse? MGRjYjQ ...

The only React element that is rendered inside a for loop is the last one

I'm struggling with a function that is supposed to render an infinite number of strings as Comment components, but it only displays the last component. This is the function I'm working with: function displayComments(...comments) { for(let i ...

Error: The 'length' property cannot be searched for using the 'in' operator

Hmm, I keep getting an error that says "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" Every time I attempt a $.each on this JSON object: {"type":"Anuncio","textos":["Probando ...

JQuery Function for Repeatedly Looping through Div Elements

I've been experimenting with creating a loop that alternates the fade-in and fade-out effects for different elements. This is what I have so far: setInterval(function() { jQuery(".loop").each(function(index, k) { jQuery(this).delay(1200 ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

Updating the background of a button with Vue JS by utilizing an object upon clicking

If you have three buttons and want to change the background color when clicked, for example, clicking on the red button should turn the background color red. However, there is an important detail here: if you click on one button and then another, the old c ...

Vercel is encountering difficulty locating a module or type declaration during the construction of a Next.js application

Currently, I'm facing an issue while trying to deploy a Next.js app to Vercel. The package react-swipeable appears to have its own type declarations but the build fails with the following error: Running "npm run build" ... > next build ... Failed t ...

Unexpected appearance of a blue line in Material UI when the overflow attribute is included

For my React application, I've integrated Material-UI along with styled components. The strange thing is that when I use a Chrome browser to view the app, I encounter an issue that doesn't seem to happen in Firefox. The problem arises when I add ...

Dealing with API fetch errors using dynamic URLs in Axios

When attempting to retrieve data from an API with a URL containing a user-input string, the application crashes if the entered string is invalid. This crash results in the error message "TypeError: Cannot read properties of null (reading 'map')". ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

When Index.html is hosted via Express, the component fails to render

Following a tutorial has led me to the end and I've made changes to my App.js as shown below: import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <p>lm ...

Sending an Angular $http post request to a MVC action but the parameter is coming through as

After posting this content: $http.post(Common.blog.save, { blog: blog }) .then(saveBlogComplete) .catch(function(message) { }); The Fiddler output I receive is as follows: {"blog":{"title":"Chicken Is Good","content":"#Chicken Is Good\ ...

A guide on incorporating router links within a list component in a React project

In one of my projects, I've implemented a navbar with a profile icon that expands to show four different options: "Log in", "Register", "Edit", and "Admin". However, I'm facing an issue where clicking on these links doesn't always redirect m ...

Utilizing Formik for React Native form validations

Hey there! I recently implemented formik validations in my application to handle TextInput validations. Everything is working smoothly and I can retrieve the entered values. However, I'm facing an issue with a dropdown component where I use react-nati ...

How can I achieve auto-refresh functionality in SQLite using PHP and JavaScript without refreshing the entire page

I am currently working with a straightforward php code that retrieves data from a SQLite database by using the query "$query ="Select A from B"". The process works smoothly, and upon updating the SQLite database, I can refresh the page to display the new d ...