Removing unwanted users in a React application

Recently, I started working with React. There's a project where I need to filter users based on their upvotes, with the user having the most upvotes appearing at the top. However, I'm struggling to implement this feature properly. Additionally, whenever I interact with one user (e.g., upvoting), it affects all other users as well. Can anyone provide guidance on what might be going wrong or how I can fix these issues?

 import React from 'react';
 import Nav from './Nav';
 import './App.css';
 import react,{Component} from'react'

const Items = [
{
  img: "https://pbs.twimg.com/profile_images/1219033860991848448/UKWAPwfG_400x400.jpg",
  header:"Netlify, our Conversion from Angular to React",
  website:"netlify.com",
  timeAuthor:"Submitted  9 hours ago by brianlammar",

},
{
  img:"https://pbs.twimg.com/profile_images/1825094360/random_dude_400x400.jpg",
  header:"React in patterns - List of design patterns ragaca",
  website:"github.com",
  timeAuthor:"Submitted 9 hours ago by  magenta_placenta",

},
{
  img:"https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/c8366146-25b7-49b3-a640-58439d2a2baa/d5gs9sv-0c98ab64-0f32-4c6d-90ed-39d38d2bf0ba.jpg/v1/fill/w_900,h_675,q_75,strp/random_dude_who_lives_near_me_by_misa_amane_17_d5gs9sv-fullview.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7ImhlaWdodCI6Ijw9Njc1IiwicGF0aCI6IlwvZlwvYzgzNjYxNDYtMjViNy00OWIzLWE2NDAtNTg0MzlkMmEyYmFhXC9kNWdzOXN2LTBjOThhYjY0LTBmMzItNGM2ZC05MGVkLTM5ZDM4ZDJiZjBiYS5qcGciLCJ3aWR0aCI6Ijw9OTAwIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmltYWdlLm9wZXJhdGlvbnMiXX0.YP5o5wapk-q4-6vpQIKaERchdyvNl8MOAs_cbG7ThfU",
  header:"Redux vs Mobx vs Flux vs... Do you even...",
  website:"goshakkk.name",
  timeAuthor:"Submitted 8 hours ago by goshakk",

}
]
  class App extends Component{
    
   constructor(props){
     super(props)
     this.state= {
       count:0 
     }
   }
   incremento(){
     this.setState({
       count:this.state.count + 1
     })
   }
   decremento(){
     this.setState({
       count:this.state.count -1 
     })
   }
  
   render(){

    
     return (
    
    Items.map(item =>{
      return (
        <div>
          <div className='section'>
          <span className='Votes'>
          <i  onClick={() => this.incremento()}  className="fas fa-arrow-up"></i>
          <p>{this.state.count}</p>
          <i  onClick={() => this.decremento()} className="fas fa-arrow-down"></i>
          </span>
          <img src={item.img}  />
          <div className='Content'>
            <h1 className='h'>{item.header}</h1>
            <p>{item.website}</p>
            <p>{item.timeAuthor}</p>
            <span className='lil'>
            <p className='red'>10 Comments</p>
            <p>share</p>
            <p>save</p>
            <p>hide</p>
            <p>report</p>
            <p>pocket</p>
            </span>
          </div>
          </div>
        </div>
      )
    
      })
     )
    }
  }
 
  
 
export default App;

Answer №1

Here is an example of how the code should appear: https://example.com/gracious-glitter-x283l?file=/src/App.js

 import React, { useState } from 'react';
import Header from './Header';
import './App.css';


const Data = [
    {
      id: 1,
      count: 0,
      img:
        "image-url-1.jpg",
      title: "React Hooks - A Beginner's Guide",
      website: "reactjs.org",
      submittedBy: "Submitted 7 hours ago by user123"
    },
    {
      id: 2,
      count: 0,
      img:
        "image-url-2.jpg",
      title: "Styled Components vs Emotion - A Comparison",
      website: "css-tricks.com",
      submittedBy: "Submitted 6 hours ago by design_guru"
    }
  ],
  Post = ({ adjustCount, data }) => (
    <div>
      <div className="post-section">
        <span className="Votes">
          <i
            onClick={() => {
              adjustCount(1);
            }}
            className="fas fa-arrow-up"
          >
            UP
          </i>
          <p>{data.count}</p>
          <i
            onClick={() => {
              adjustCount(-1);
            }}
            className="fas fa-arrow-down"
          >
            DOWN
          </i>
        </span>

        <img src={data.img} />
        <div className="PostContent">
          <h1 className="Title">{data.title}</h1>
          <p>{data.website}</p>
          <p>{data.submittedBy}</p>
          <span className="Info">
            <p className="Comments">5 Comments</p>
          </span>
        </div>
      </div>
    </div>
  );

const App = () => {
  const [posts, setPosts] = useState(Data);

  return (
    <>
      {posts
        .sort((a, b) => (a.count < b.count ? 1 : -1))
        .map((data) => (
          <Post
            data={data}
            adjustCount={(value) => {
              const index = posts.findIndex((d) => d.id === data.id),
                newData = [...posts];
              newData[index].count = newData[index].count + value;
              setPosts(newData);
            }}
          />
        ))}
      ;
    </>
  );
};

export default App;

Answer №2

The number of users is rising because the count that is being maintained is not specific to individual users, but rather a general counter.

Instead of this approach, consider:

  1. Removing the current count state.
  2. Introducing a new state called 'users', which will store an array of user objects, each with their own count property.

this.state = Items.map(i => ({...i, count: 0}))

  1. Modify the incremento(id) and decremento(id) methods to accept an id parameter.
  2. With this adjustment, you can update the count for the specific user whose button was clicked in the respective methods.
  3. In the render method, sort the `Items` array by the count field and then display each user accordingly.

By implementing these changes, you can ensure that the count only increases for the selected user, and display users sorted by counts in descending order.

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

Is there a way to automatically trigger a function once another function has completed its execution?

I am diving into the world of JavaScript as a beginner. All I want to do is trigger the function called seconOne() right after the execution of firstOne(). Specifically, I need the function two to be invoked when the value of p1 reaches 4. While I can us ...

A guide to displaying a countdown timer in an Angular application during the app's loading process

Displaying a loader that shows the time in seconds while loading an app is my goal. Here is the code snippet: HTML <body> <div class="app-loader"> <div class="loader-spinner"> <div class="loading-text"></div> ...

Rendering React components and filtering arrays from the fetched data

Just starting out with React so please be patient with me. I've fetched a list of data from a server and stored it in the State using the componentDidMount function. I populate my State array named solo with the data. Everything works fine until I att ...

CSS: Adjusting the vertical position of text without affecting the background

I am currently working on some CSS buttons that expand in size when hovered over. I have successfully increased the text size as well, but now I am facing an issue with aligning the text a few pixels lower without affecting the background image layout. Ca ...

How come the checkboxes for trees are not being checked in the child component while using Ant Tree Design?

I'm currently troubleshooting an issue with the Ant Tree component. I have a setup where the PageAdmin component fetches data for selected nodes in the tree, stores it in the checkedKeys array, and passes it as props to the CustomTree component. While ...

Extracting values from a JSON object in JavaScript

Is there a way to retrieve the _id and state values from the provided data? Check out the data { "data": { "totalSamplesTested": "578841", "totalConfirmedCases": 61307, "totalActiveC ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...

Adjusting Specific Time for Jquery to Change Date if Less Than X Value

Creating a carousel to display featured content for Friday nights. Initially, upon loading the page, I automatically trigger a click to show the upcoming Friday night's content based on the current date and time using new Date(). However, our clients ...

retrieving JSON information from a PHP endpoint

My PHP webpage is returning a JSON string. I created a function to retrieve this data and display it on a jQuery Mobile listview. function LoadJsonDataFunction() { $.getJSON("my_web_page.php", function(obj) { $.each(obj, function(key, value){ ...

Accessing data from datatables in a typescript component in HTML format

I need to retrieve the selected mfRowsOnPage data, which is currently set at 10. The user can later choose a different value such as 5 or 15. I also require information on which page the user is viewing, for example, the 1st or 2nd page. This is the table ...

Webpack encounters issues when compiling ES6 syntax from external packages

I am encountering an issue with integrating an ES6 npm package, specifically one called gamesystem, into my project and building it with webpack (along with babel). For some reason, the build fails to process any ES6 code within the external dependency. Ho ...

When making an HTTP GET request followed by another GET request in Express, it results in an error with undefined parameters on the

When I open a form that has a link to a list and try to access the list, I encounter an "id" undefined error for the form we came from, which was already functional. The issue arises when I have a GET page where I present a form to modify a record at /loc ...

What is the best way to make an HTML table with a static header and a scrollable body?

Is there a way to keep the table header fixed while allowing the table body to scroll in an HTML table? Any advice on how to achieve this would be greatly appreciated. Thanks in advance! ...

Send the update password information in a Bootstrap modal using ajax

I have created a change password form and implemented Ajax submission along with validation. Below is the code I wrote. Is there a way to use this Ajax function for multiple modal forms, or do we need to create separate functions for each modal form? Addi ...

Incorporating React Bootstrap into a component for stylish card designs

It would be great if the cards could be displayed in rows of 4 on the page. However, I encountered an error: An error occurred during compilation of MyDishes.js file. The error message reads: SyntaxError: /Users/adiskop/zestie-frontend/src/components/MyDi ...

Not a modal or popup-style window

Can a non-modal or pop-up window be generated using jquery in JSP? I aim to display detailed information to the user in a separate window without obstructing the main page. I prefer not to open a new tab or browser window, so it should function like a mo ...

Information briefly appears in the console before vanishing

I've been working on a signin and register form using React. In the signin component, I'm encountering an issue where I try to post data to my database using fetch, but when I log the response promise in the console, it disappears almost instantl ...

Troubleshooting issues with ng-options not correctly updating ng-model in AngularJS when using ajax requests

I have a question regarding my logic that I can't seem to figure out. In this Fiddle example, everything works fine without using AJAX or a timeout. However, when I try to implement the same logic with a timeout/ajax, the expected behavior does not o ...

Modify the selected toggle buttons' color by utilizing the MUI ThemeProvider

I am currently working on customizing the color of selected toggle buttons within my React app using TypeScript and ThemeProvider from @mui/material 5.11.13. Despite my efforts, when a toggle button is selected, it still retains the default color #1976d2, ...

Issue with Path Alias Functionality in Bun Project Despite Accurate Configuration

I followed a guide to configure path alias at , but unfortunately, it's not working as expected. Recently I started a new Bun project with the intention of migrating a Node app to Bun. Here are the steps I took: Create a directory and initialize t ...