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

Manipulate the inner HTML of a ul element by targeting its li and a child elements using JQuery

Here is the HTML code I am working with: <ul class="links main-menu"> <li class="menu-385 active-trail first active"><a class="active" title="" href="/caribootrunk/">HOME</a></li> <li class="menu-386 active"> ...

(Processing) Eliminating Previously Utilized Element from Array

Apologies for the poorly worded title. I'm working on a "War" game in Processing for my Programming course. I need help modifying my code to remove each used card from the deck/array. I've come across some references to "ArrayList" in online post ...

Using JavaScript with React to invoke an asynchronous action within a component

Within my class, I have implemented some asynchronous actions in the ComponentDidMount method. The code snippet looks like this: componentDidMount(){ // var my_call = new APICall() Promise.resolve(new APICall()).then(console.log(FB)) } class API ...

Pulling down the data with Ajax "GET"

When a user clicks on a button, a zip file will be downloaded. I have the necessary components in place, but I am struggling to ensure they work together seamlessly. The "GET" call will retrieve byte content with the content type specified as application/ ...

Incorporated asynchronous functionality, struggling to integrate it into the code

Previously, I used to utilize the following code for handling state: //get state MyClass.prototype.getState = function(key) { var value; switch(this._options.type){ case "cookie": value = $.cookie(key); ...

What steps can be taken to resolve the error message "Warning: useLayoutEffect does not have any effect on the server"?

Here is the error message I keep encountering: Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and ...

How to extract the date value from an HTML date tag without using a datepicker

Utilizing Intel's app framework means there is no .datepicker method available. The following code snippet generates the date widget within my app: <label for="startdate">Start Date:</label> <input type="date" name="startdate" id="star ...

Trouble with minified scripts on a particular server

Apologies if this has already been addressed, but I've been searching for a solution for hours. I created a basic website that works perfectly on my own hosting. However, when I transfer it to new hosting (same company, same package, different server ...

Using Ajax.ActionLink to pass a parameter in JavaScript

When I call a controller in this manner: @Ajax.ActionLink("Clients", "ClientAccountsPartialView", new { entityCode = -1, taxNumber = -1, country = 1, ...

Synchronize information between two drop-down lists

I am currently utilizing the boostrap library to create a pair of dropdown lists. My goal is to have the items in the second dropdown list dynamically update based on the selection made in the first dropdown. Within my code, there exists a dictionary name ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...

Latest news on KnockoutJS enhancements

Is there a way to create an HTML markup with a GIF progress bar that appears when the page is loading? I want to use Ajax to fetch data, populate the markup, and then hide the GIF. How can I achieve this functionality using KnockoutJS? var Item = functi ...

Steps for inserting a button within a table

Currently, I have implemented a function that dynamically adds the appropriate number of cells to the bottom of my table when a button is clicked. This is the JavaScript code for adding a row: <a href="javascript:myFunction();" title="addRow" class= ...

How to create a 3D array in PHP using CodeIgniter?

How can I create a 3-dimensional array? I have two tables, links and hashtags, where a link can have multiple hashtags associated with it. How do I go about generating an array structure like the one shown below? Desired 3D Array Output: Array ( [0] =&am ...

My webpage layout doesn't quite accommodate my content, so I need to adjust it to be more zoom

Why does the page container load bigger than the html/body container in mobile mode, as shown in the photo? Here is my CSS: html { margin-top: 48px; width: 100%; } body { margin: 0; width: 100%; background: var(--bgGray); font-family: Ub ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

The JADE form submission is not being captured even though the route is present

I am currently utilizing JADE, node.js, and express to develop a table for selecting specific data. This entire process is taking place on localhost. The /climateParamSelect route functions properly and correctly displays the desired content, including URL ...

Chrome-specific bug in DataTable sorting with jQuery - looking for workaround to fix the issue

Here is my code snippet: jQuery.fn.dataTableExt.oSort['num-asc'] = function(a,b) { var x = a.replace( /<.*?>/g, "" ); var y = b.replace( /<.*?>/g, "" ); x = parseFloat( x ); y = parseFloat( y ); return ((x < y ...

Using a function to send multiple child data in Firebase

I am trying to figure out how to save data to a Firebase multi-child node structure: --Events ----Races -------Participants Below is some dummy data example that represents the type of data I need to store in Firebase: var dummyData = [ { ...

Is it possible to animate CSS Grid components?

Is it possible to animate a re-ordered set of elements in an array that are arranged using a CSS Grid layout? Check out this quick boilerplate ...