0

I am stuck on this for some reason. I know how to use .sort when there is a simple array. I am not quite sure how to sort a nested object in an array using a variable in that object. I can sort it, but I am not sure how to display it.

Here is what I am working with. I get data from a database and map over that data to display it. Everything works as expected. Now I want to take that data and sort it by artist.

Here is the code I am working with.

export default function ShowRecords() {
  const classes = recordFormStyles();
  const url = " http://localhost:5000";

  //get userData state to use in useEffect

  //set state for showing records in database and opening/closing modals

  const [newRecords, newRecordData] = React.useState([]);

  const [editOpen, handleEditModal] = React.useState(false);

  const [addModalOpen, handleAddModal] = React.useState(false);

  //set state for edit records

  const [title, setTitle] = React.useState("");

  const [artist, setArtist] = React.useState("");

  const [rating, setRating] = React.useState("");

  const [genre, setGenre] = React.useState("");

  const [description, setDescription] = React.useState("");

  const [userId, setUserId] = React.useState("");

  //set state for favorite icon

  const [favorite, setFavorite] = React.useState([]);

  const fetchFavoriteData = async () => {
    const result = await axios.get(url + "/favorite/get", authToken);

    setFavorite(result.data);
  };

  const addFavorites = async (_id, title, artist, rating, genre, description, isFavorite) => {
    const favorites = {
      userId: _id,
      title,
      artist,
      rating,
      genre,
      description,
      isFavorite
    };

    const result = await axios.post(
      url + "/favorite/add",
      favorites,
      authToken
    );

    setFavorite(result.data);
    
  };

  const deleteFavorite = async (title) => {
    await axios.delete("http://localhost:5000/favorite/delete", {
      data: { title: title },
      authToken,
    });
  };

  //functions to control state

  const handleAddModalOpen = () => {
    handleAddModal(true);
  };

  const handleCloseAddModal = () => {
    handleAddModal(false);
  };

  const handleIsEditModalClose = () => {
    handleEditModal();
  };

  //fetch record data

  const fetchData = async () => {
    const result = await axios.get(url + "/record/get", authToken);
    newRecordData(result.data);
  };

  React.useEffect(() => {
    fetchData();
    fetchFavoriteData();
    
  }, []);

  // delete records

  const deleteRecord = async (_id) => {
    const deleteRecords = {
      _id: _id,
    };

    await axios.delete(url + "/record/" + _id, deleteRecords).then((result) => {
      const refresh = newRecords.filter((result) => result._id !== _id);
      newRecordData(refresh);
    });
  };

  //functions for controlling edit record state

  const editRecord = (_id, title, artist, rating, genre, description) => {
    setUserId(_id);
    setTitle(title);
    setArtist(artist);
    setRating(rating);
    setGenre(genre);
    setDescription(description);
    handleEditModal(true);

    console.log(title);
  };

  //functions for setting favorite state and color and post request to add favorite

  return (
    <div>
      {/* set props */}

      <Favorites />
      <AddRecord
        isAddModalOpen={addModalOpen}
        handleIsAddModalClose={handleCloseAddModal}
        addNewRecords={newRecords}
        handleIsAddModalOpen={handleAddModal}
        refreshRecordData={newRecordData}
      />
      <EditRecords
        editModalOpen={editOpen}
        handleCloseEditModal={handleIsEditModalClose}
        editUserId={userId}
        editTitle={title}
        editArtist={artist}
        editRating={rating}
        editGenre={genre}
        editDescription={description}
        editTitleState={setTitle}
        editArtistState={setArtist}
        editRatingState={setRating}
        editGenreState={setGenre}
        editDescriptionState={setDescription}
        editUrl={url}
        editFetchData={fetchData}
        editNewRecordData={newRecordData}
      />
      <Button
        className={classes.addButton}
        onClick={() => handleAddModalOpen(true)}
      >
        Add Record
      </Button>

      <div className={classes.cardsContainer}>
        <Grid container spacing={8} style={{ padding: 80 }} justify = "center">
          {newRecords.length > 0 &&
            newRecords.map((element) => (
              <RecordCard
                key = {element._id}
                element={element}
                editRecord={editRecord}
                deleteRecord={deleteRecord}
                addFavorites = {addFavorites}
                deleteFavorite = {deleteFavorite}
                favorite = {favorite}
              />
            ))}
        </Grid>
      </div>
    </div>
  );
}

I get the data in my uesEffect and I want to sort it using the Arist name. I am just unsure on how to do that. I couldn't find much googling.

2
  • Unrelated to your question which is already answered, but if you are using a lot of state variables, you may consider using a reducer instead Commented Feb 23, 2021 at 18:40
  • I plan to refactor using redux. This was a project I did before learning all of that. Commented Feb 23, 2021 at 18:43

1 Answer 1

1

Sort the data before you save it into state. The sort function can take in a function that returns -1, 0, 1 to determine how things should be ordered. The below example uses the localeCompare function to sort by the artist.

let data = [
  { artist: 'john', record: '1' },
  { artist: 'mary', record: '2' },
  { artist: 'bob', record: '3' }
];

let sorted = data.sort((a,b) => (a.artist.localeCompare(b.artist)));

console.log(sorted);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.