1

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;

1 Answer 1

1
  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);
      })
...

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

2 Comments

I have to use redux to sort. Thanks for the above solution. Could you please let me know how to sort using redux? I have installed redux as of now
you can sort -> save to store using reducer. redux.js.org/tutorials/fundamentals/…

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.