The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button.

Although I managed to get a sorted array displayed in the console log using the handle function, the UI did not reflect these changes. I seem to be missing something in my code and would greatly appreciate any help or guidance.

function App() {
  const baseURL = `https://randomuser.me/api`;
  const [profiles, setProfiles] = useState([]);
  const [singleProfile, setSingleProfile] = useState([]);

  const showProfiles = useCallback(() => {
    axios.get(baseURL).then((response) => {
      setProfiles(response.data.results);
    });
  }, [baseURL]);

  const showProfile = useCallback(() => {
    axios.get(baseURL).then((response) => {
      setSingleProfile(response.data.results);
    });
  }, [baseURL])

  useEffect(() => {
    showProfiles();
    showProfile();
  }, [showProfiles, showProfile]);

  const deleteProfile = (profileId) => {
    setProfiles(prevState => prevState.filter(profile => profile.id.value !== profileId))
  }

  const addProfile = () => {
    showProfile();
    setProfiles(prevState => [...prevState, ...singleProfile]);
  }

  const handleSortByAge = () => {
    const profilesSortedByAge = profiles.sort((a, b) => {
      if (a.dob.age > b.dob.age) {
        return 1;
      } else {
        return -1;
      }
    })
    console.log('click and profiles', profiles);
    return setProfiles(profilesSortedByAge);
  }

  const handleSortByLastName = () => {
    const profilesSortedByLastName = profiles.sort((a, b) => {
      if (a.name.last > b.name.last) {
        return 1;
      } else {
        return -1;
      }
    })
    setProfiles(profilesSortedByLastName);
  }

  if (!profiles) return null;

  return (
    <div className="App">
      <ProfilesPage
        profiles={profiles}
        showProfiles={showProfiles}
        deleteProfile={deleteProfile}
        addProfile={addProfile}
        setProfiles={setProfiles}
        handleSortByAge={handleSortByAge}
        handleSortByLastName={handleSortByLastName}
      />
    </div>
  );
}

export default App;

Answer №1

When using Array.prototype.sort, keep in mind that it performs an in-place mutation of the array. Creating a new array reference is essential for React's reconciliation process. To achieve this, make sure to create a shallow copy before sorting.

Here's an example of how to properly sort by age:

const handleSortByAge = () => {
  const profilesSortedByAge = profiles
    .slice()
    .sort((a, b) => {
      if (a.dob.age > b.dob.age) {
        return 1;
      } else {
        return -1;
      }
    })
  console.log('click and profiles', profiles);
  return setProfiles(profilesSortedByAge);
}

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

Shattering the barrier

When using the bubble chart, I encountered an issue with adding line breaks in text. No matter what I tried, such as using \n or , it consistently showed me an error. import React from 'react'; import { BubbleChart,key,data } from 're ...

Vuetify: Utilizing Time Range Inputs for Start and End Time

I am encountering some difficulty in identifying what I may have missed. I am dealing with 2 inputs: time, startTime, and endTime startTime <v-col cols="12" sm="6" md="2"> <v-menu ref="menu" ...

Tips to prevent the @click event from firing on a specific child component

When I click on any v-card, it redirects me to a different link. However, if I click on the title "World of the Day", I don't want anything to happen. How can I prevent being redirected when clicking on the title? template> <v-card clas ...

Disabling the authentication prompt in the browser

Apologies for the repetition, but I would like to pose a more general question. Is there any method on the client side of a web application to predict if requesting a resource will result in a 401 status code and trigger an unattractive authentication pro ...

Is there a way to position Drawer beneath AppNar in Material UI without relying on outdated makeStyles method?

Currently utilizing the latest React v18 with Material UI, I have encountered an issue where makeStyles is deprecated for this particular version of React in Material UI. I need assistance on how to properly clip Drawer under the AppBar. While there are n ...

Create a filter system using a MERN stack that incorporates regex, a search box,

In an effort to understand how the MERN stack operates as a cohesive unit, I have taken on a hands-on approach by following tutorials from bezcoder. These include guides on Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code). Sam ...

What is the best method for compressing and decompressing JSON data using PHP?

Just to clarify, I am not attempting to compress in PHP but rather on the client side, and then decompress in PHP. My goal is to compress a JSON array that includes 5 base64 images and some text before sending it to my PHP API. I have experimented with l ...

What is the best way to showcase two SVG clocks on a single webpage?

The issue arises when combining the desktop and mobile versions of the clock script. The first clock works fine on its own, but upon duplicating another set of scripts for the second clock, it encounters display problems. I have appropriately labeled the c ...

NextJS hot reload with Docker is a powerful combination for seamless development environments

I've encountered issues trying to configure hot reload with Docker and NextJS. When I make changes and save a file, the server does not reload. Below is the contents of the docker-compose.yml: version: '3' services: mainapp: build: ./ ...

Prevent the hover() effect from affecting all div elements at once

I am aiming to achieve a function where hovering over a div with the "rectangle" class will display another div with the "description" class. Initially, the description div will have a display value of "none", but upon hovering, it should become visible. ...

Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data. var app = angular.module("Recib ...

Vue table displaying a list of books with a button that allows users to easily send the title of the

Hey everyone, I am new to Vue and struggling with a certain task. I have two tables: Books and Booking. Books: ID, NAME, AUTHOR etc. Booking: ID, ID_USER, ID_BOOK I'm creating a page in Vue that displays all bookings, but the table only shows the BOO ...

Exploring the power of Angular JS promises through ng-repeat

My current project involves fetching latitude and longitude coordinates from a postcode using an API, then utilizing those coordinates to retrieve data on street level crimes near that location on a specific date through the UK police API. However, I have ...

Unable to Retrieve Response from jQuery AJAX in a Function

Having some trouble with a jQuery AJAX function that is supposed to retrieve data from a file. I can't seem to get the function to return the actual value. Any suggestions? $(document).ready(function () { function fetchData() { ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

React is displaying [object Object] instead of the intended value on the webpage. What steps can be taken to resolve this issue?

I have attempted to retrieve data from an API and am currently working on displaying this data within a table cell inside a component. Instead of rendering the original data, React is displaying [object Object]. I tried using the join() method with commas ...

Having trouble getting my Jquery Ajax post request to work with JSON data

I am working on syncing data from my Phonegap app back to the server. I have a PHP script set up on the server to handle the incoming data and now I need to figure out how to post values from my App to this script. Currently, I store my data in a SQLite d ...

Repetitive NodeJS event triggers within Electron-React application causing unexpected behavior

In my custom software package (referred to as PACKAGE_A), I have implemented various automated tasks using a node script. This package includes a Notifier module that creates and exports an EventEmitter. (The entire project is structured as a Monorepo) co ...

The yarn installation process is not utilizing the latest available version

Working with a custom React component library my-ui hosted on a personal GitLab instance. In the package.json, I include the library like this: "my-ui": "git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6 ...

Is it possible to redefine a function that is attached to $ctrl outside of the AngularJS framework?

Within my DOM, there exists an element containing ng-click="$ctrl.goToHome(), which is connected to the logo on my site. This particular element is generated by a third-party AngularJS application. The complete element can be seen below: <img ng-if=":: ...