sud
sud

Reputation: 45

How can I add sorting using Redux?

How can I add sorting for API returning a JSON array? I'm new to Redux. I have installed the redux. Could someone tell me what's the best method to follow?

Thanks for your help.

import React, { useState, useEffect } from "react";
import Post from "../../Components/Post/Post";
import axios from "axios";

const HomePage = () => {
  const [posts, setPosts] = useState("");

  let config = { Authorization: "............." };
  const url = "..........................";

  useEffect(() => {
    AllPosts();
  }, []);

  const AllPosts = () => {
    axios
      .get(`${url}`, { headers: config })

      .then((response) => {
        const allPosts = response.data.articles;
        console.log(response);
        setPosts(allPosts);
      })
      .catch((error) => console.error(`Error: ${error}`));
  };

  return (
    <div>
      <Post className="Posts" posts={posts} />
    </div>
  );
};

export default HomePage;

Upvotes: 1

Views: 164

Answers (1)

igorves
igorves

Reputation: 591

  1. You don't have redux here. Do you need it?
  2. If you want to sort result and save sorted results to state:
...
 .then((response) => {
        const allPosts = response.data.articles;
        // sort the result here
        const sortedPosts = allPosts.sort((a,b) => 
          // comparer
        );
        setPosts(sortedPosts);
      })
...

Upvotes: 1

Related Questions