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
|
13 Discussions
|
Please Login in order to post a comment
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;
My solution, const handleMostUpvoted = () => { // Logic for most upvoted articles SetArticles(prevState => [...prevState].sort((a,b) =>b.upvotes- a.upvotes)); };
const handleMostRecent = () => { // Logic for most recent articles SetArticles(prevState => [...prevState].sort((a,b) =>new Date(b.date) - new Date(a.date))); };
I solved the problem, with an accepted Submission, but the status of the challenge is still to "Try Again" instead of "Solved".
I don't understant if I have to provide a better solution, or if it's a bug of the platform.
Furthermore, what would a "better solution" mean ???