What is the best way to rearrange elements within an object when there is no predetermined starting order?

Someone assisted me in refining this code snippet

import React, { useEffect, useState } from "react";
import _ from "lodash";

// const SeleccionClientes = "";
const items = [
  {
    client: "Microsoft",
    idClient: 0,
    idProjectType: 1,
    projectType: "traditional",
    title: "React Native App"
  },
  {
    client: "Amazon",
    idClient: 1,
    idProjectType: 1,
    projectType: "traditional",
    title: "ServerSide OPS"
  },
  {
    client: "KFC",
    idClient: 2,
    idProjectType: 4,
    projectType: "traditional",
    title: "QR Reader"
  },
  {
    client: "KFC",
    idClient: 2,
    idProjectType: 1,
    projectType: "traditional",
    title: "React Native App"
  },
  {
    client: "KFC",
    idClient: 2,
    idProjectType: 1,
    projectType: "traditional",
    title: "React KKL"
  },
  {
    client: "PEICI",
    idClient: 3,
    idProjectType: 1,
    projectType: "traditional",
    title: "KuKluxKlan"
  }
];

export default function ListView() {
  const [list, setList] = useState(items);
  const [idClient, setIdClient] = useState(2);

  const displayProjectsForClient = idClient => {
    return list.filter(item => item.idClient === idClient);
  };
  const displayedProjects = displayProjectsForClient(idClient);

  // equivalent to componentDidMount()
  useEffect(() => {
    setList(displayedProjects);
  }, []);

  const updateFav = (val, ind) => {
    const tempData = _.cloneDeep(list);
    tempData[ind].fav = val;
    setList(tempData);
  };

  const favItems = _.filter(list, item => item.fav);
  const finalObject = { [new Date().toISOString()]: favItems };

  return (
    <div>
      Selected Client: "KFC"
      <br />
      Add Favorite Projects:
      {displayedProjects.map((item, index) => {
        return (
          <div
            key={index}
            style={{ margin: "5px", padding: "5px", background: "#D6D6D6" }}
          >
            <div>{item.title}</div>
            {`Project ID ${item.idProjectType}`}
            <input
              type="checkbox"
              value={item.fav}
              onChange={e => updateFav(e.target.checked, index)}
            />
          </div>
        );
      })}
      <div>
        Active projects (final object): <br />
        {JSON.stringify(finalObject, null, 2)}
      </div>
    </div>
  );
}

Instead of using the input checkbox, I opted for the react-native-elements switch component, but it doesn't seem to be functioning as expected. It appears that the issue may be related to the absence of a "fav" property in the item object.

This is the revised code section

        <FlatList
          data={dataSource}
          renderItem={({item, index}) => (
            <ListItem
              containerStyle={{backgroundColor: '#fafafa', width: wp('87.1%'), height: 64, alignItems: 'center', justifyContent: 'center', alignSelf: 'center', marginTop: hp('2.8%'), paddingHorizontal: 0}}
              topDivider={false}
              bottomDivider={true}
              titleStyle={{
                marginLeft: 0,
                fontSize: rfv(16),
                fontWeight: "normal",
                fontStyle: "normal",
                textAlign: "left",
                color: "#707070"
              }}
              subtitleStyle={{
                marginLeft: 0,
                fontSize: rfv(14),
                fontWeight: "normal",
                fontStyle: "normal",
                textAlign: "left",
                color: "#c4c4c4"
              }}
              title={`${item.title}`}
              subtitle={`ID ${item.idCliente}`}
              switch={{
                trackColor: { false: "#767577", true: "#81b0ff" },
                thumbColor: item.fav == true ? "#1062cc" : "#f4f3f4",
                ios_backgroundColor: "#9e9e9e",
                value: item.fav == undefined ? false : true, 
                onValueChange: () => {e => console.log(updateFav(e.target.checked == undefined ? false : true, index))}
              }}
            />
          )}
        />

The current implementation successfully lists the projects, but when I interact with a switch, it generates a fresh object based on that selection. Unfortunately, the switches revert to their original positions immediately.

I neglected to mention, here is the function definition

  const updateFav = (value, index) => {
    const tempData = _.cloneDeep(dataSource);
    tempData[index].fav = value;
    setDataSource(tempData);
  };

  const favItems = _.filter(dataSource, item => item.fav);

Answer №1

Your code is a mix of React (HTML) and React Native, which may be causing the issue. To fix it, you need to adjust your Switch function. There's no need to check for true or false conditions.

   switch={{
        trackColor: { false: "#767577", true: "#81b0ff" },
        thumbColor: item.fav == true ? "#1062cc" : "#f4f3f4",
        ios_backgroundColor: "#9e9e9e",
        value: item.fav, 
        onValueChange: () => {updateFav(!item.fav, index)}
      }}

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

How to Centre Align Items in a React Native ListView

Is there a way to center align the items in a ListView without using another View wrapping the ListView? Currently, all the items are left aligned. ListView Code Snippet <ListView dataSource={this.state.dataSource} renderRow={this.renderItem} ...

Are there any JavaScript libraries available that can mimic SQLite using localStorage?

My current application makes use of SQLite for storage, but I am looking to switch it up to make it compatible with Firefox and other browsers. I've been considering localStorage as an option. However, I've noticed that localStorage lacks some o ...

The test is failing to execute the service mock promise due to an issue with the `

A problem has arisen while creating a mock for the BoardService. It appears that the .then function is not executing in the controller during testing, even though it works perfectly fine in the live application. Below is the test snippet: beforeEach(inje ...

Nesting objects within arrays using Typescript Generics

Hello, I am currently attempting to assign the correct type to an object with nested values. Here is a link to the code in the sandbox: https://codesandbox.io/s/0tftsf interface Product { name: string, id: number productList?:ProductItem[] } interf ...

Exploring JavaScript and accessing objects

I'm currently working on a small file-manager project in JavaScript and I've encountered an issue with the code. In the `get()` function, I am trying to access the `Content.files` array but it seems like there's some problem with variable sc ...

Generating a JSON Array by aggregating data from a loop with the help of the Spring Boot framework

Recently, I successfully implemented a code to import data from a .pcap file. The code works flawlessly as it reads the cap files and displays the results in the console. The implementation of this code can be seen below: @SpringBootApplication public cl ...

Updating an array in Vue.js without the need to reload all the data

Recently delving into Vue.js and JavaScript, I'm seeking guidance on updating an array (on Add/Edit/Delete) without having to reload all the data. The goal is to load all data only when initially opening the page with Addresses. Take a look at my cod ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

Exploring the world of AngularJS 1.3 with the exciting anticipation of the upcoming release of Angular 2 in just one year

Currently contemplating learning AngularJS 1.3, but concerned about the upcoming release of version 2 and the significant changes that will come with it. Is it worth investing time and effort into mastering a framework that is soon to be obsolete? Seekin ...

Automatic browser refresh with the `bun dev` command

Currently experimenting with the latest bun platform (v0.1.6) in conjunction with Hono. Here are the steps I followed: bun create hono test-api cd test-api bun dev After running the server, the following message appears: $ bun dev [1.00ms] bun!! v0.1.6 ...

`How to utilize the spread operator in Angular 4 to push an object to a specific length`

One issue I'm facing is trying to push an object onto a specific index position in an array, but it's getting pushed to the end of the array instead. this.tradingPartner = new TradingPartnerModel(); this.tradingPartners = [...this.tradingPartner ...

Is there a way to create an image gallery layout similar to Pinterest using CSS?

I am currently developing a dynamic PHP gallery that will feature thumbnails with the same width but varying heights. These thumbnails will be arranged from left to right, so I would prefer not to use a traditional five-column layout. I suspect that achiev ...

Tips for deleting on a numeric cell within ag-grid?

While exploring the functionality of AG-Grid with the example provided at this link [, I am currently experimenting with the numeric editor feature. I found this example on the official AG-Grid website [https://www.ag-grid.com/javascript-grid-cell-editor/ ...

Modify the BehaviorSubject upon clicking or focusing on the input

I have created a directive for an input field. I want to trigger a flag in another component when the input is clicked or focused upon. @Directive({ selector: '[appDatepicker]' }) export class DatepickerDirective implements DoCheck{ constru ...

What is the best way to make a CSS element move with Javascript?

Currently working on a JavaScript game where I am in need of a CSS object to replace the original JavaScript object. Specifically, I want my "sword" CSS object to move along with my player object when it is Unsheathead. All the examples I find only show wh ...

How to utilize the async pipe on an observable<Object> and connect it to a local variable in the HTML using Angular

Hey there! So, I have this observable called user$ which has a bunch of properties such as name, title, and address. component{ user$:Observable<User>; constructor(private userService:UserService){ this.user$ = this.userService.someMethodRet ...

How can I transfer information from a map to a child component?

I'm attempting to transfer a variable from a parent component to a child component using React and Typescript. In my Table component (parent), I have the following map. It sets the 'data' variable as the value of the last element in the arr ...

Challenge encountered with TypeScript integration in the controller

I am currently in the process of converting a website from VB to C# and incorporating TypeScript. I have successfully managed to send the data to the controller. However, instead of redirecting to the next page, the controller redirects back to the same pa ...

Encountering a situation where d3.events is returning null within Angular 2 TypeScript code

Seeking to enhance my d3 maps with tooltips, I came across a helpful code snippet at this link However, upon implementing the same code in an Angular 2 TypeScript file, an error emerged: Error: Cannot read property 'transition' of undefined Th ...

Selenium-Web Driver encounters an issue with reading the 'filter' property as undefined

Recently, I started working with Selenium and encountered an issue while trying to wait for a specific element to load. The error message that popped up was: (node:8472) UnhandledPromiseRejectionWarning: NoSuchElementError: no such element: Unable to ...