We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- React
- Data Handling
- Article Sorting
- Discussions
Article Sorting
Article Sorting
Sort by
recency
|
15 Discussions
|
Please Login in order to post a comment
all test cases are failing for this import "h8k-components"; import React, {useState} from "react"; import Articles from "./components/Articles";
import "./App.css";
function App({ articles }) { const [ articlesData, setArticles] = useState([...articles].sort((a, b)=> b.upvotes - a.upvotes)); const handleMostUpvoted = () => { // Logic for most upvoted articles const sortedList = [...articlesData].sort((a, b)=> b.upvotes - a.upvotes); setArticles(sortedList); };
const handleMostRecent = () => { const sortedList = [...articlesData].sort((a, b)=> new Date(b.date) - new Date(a.date)); setArticles(sortedList); }; return ( <> Sort By Most Upvoted Most Recent ); }
export default App;
Articles.js
App.js
I believe there is a problem with the initial test case.
Note that the articles are tested against the mostUpvotedArticles. If we do not fireEvent.click(mostUpvotedLink), articles will never equal to mostUpvotedLink.
Correct me if I am wrong?
import "h8k-components"; import { useState, useEffect } from "react"
import Articles from "./components/Articles";
import "./App.css";
function App({ articles }) {
const [sortArtiles, setSortArticles] = useState([]) const handleMostUpvoted = () => { // Logic for most upvoted articles let nexsortArtiles = [...articles]?.sort((a, b) => (b.upvotes) - (a.upvotes)) setSortArticles(nexsortArtiles) };
const handleMostRecent = () => { // Logic for most recent articles let nexsortArtiles = [...articles]?.sort((a, b) => new Date(b.date) - new Date(a.date)) setSortArticles(nexsortArtiles) };
useEffect(() => { if (articles.length) { setSortArticles([...articles].sort((a, b) => b.upvotes - a.upvotes)); } }, [articles]) return ( <> Sort By Most Upvoted Most Recent ); }
export default App;
WHY ALL THE TEST CASES ARE FAILING FOR THIS SOLUTION import "h8k-components"; import Articles from "./components/Articles"; import { useState, useEffect } from "react"; import "./App.css";
function App({ articles }) { console.log("🔍 Initial Articles:", articles); // Debugging
// State for sorted articles const [sortedArticles, setSortedArticles] = useState([]);
useEffect(() => { // Ensure initial articles are sorted correctly by upvotes if (articles.length) { setSortedArticles([...articles].sort((a, b) => b.upvotes - a.upvotes)); } }, [articles]);
const handleMostUpvoted = () => { console.log("🔼 Sorting by upvotes..."); setSortedArticles([...articles].sort((a, b) => b.upvotes - a.upvotes)); };
const handleMostRecent = () => { console.log("📅 Sorting by date..."); setSortedArticles([...articles].sort((a, b) => new Date(b.date) - new Date(a.date))); };
return ( <> Sort By Most Upvoted Most Recent ); }
export default App;