0

How can i add redux for sorting. I'm trying to sort using redux for api returning a JSON array. Could someone please help me as i'm new to Redux . Below the HomePage.js i have added post.js

Redux is the requirement to do the sorting. As i'm new to redux i'm unsure how to approach

HomePage.js

    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 = "https://*************";
    
      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;

Post.js
import React from "react";
import "./Post.css";
import { Fragment } from "react";

const Post = (props) => {
  const displayPosts = (props) => {
    const { posts } = props;

    if (posts.length > 0) {
      return posts.map((post) => {
        return (
          <Fragment>
            <div className="Post" key={post.title}>
              <img
                src={post.urlToImage}
                alt="covid"
                width="100%"
                className="img"
              />
              <h5 className="title"> {post.title}</h5>
              <p className="author"> {post.author}</p>
              <p className="description"> {post.description}</p>
            </div>
          </Fragment>
        );
      });
    }
  };
  return <div className="Posts">{displayPosts(props)}</div>;
};

export default Post;
  • Just want to add a comment. Please hide your authorization data and rotate the keys since you've posted to a public place. – NanoBit May 01 '21 at 04:20
  • Also, we need more information like, what does Post look like and do we really need Redux here if all you need is sorting? – NanoBit May 01 '21 at 04:22
  • @NanoBit Yes i have to do it using Redux. I'm updating the post.js as well now –  May 01 '21 at 04:23
  • @alex There is no redux involved in the code you posted. what is the expectation? You want to store the data sorted or load the data as sorted when reading? – Ravi Theja May 01 '21 at 04:31
  • @RaviTheja Yes there is no Redux involved in the code i have shared. I'm seeking help for that how to approach. ''load the data as sorted when reading" . I'm new to redux. could you please help –  May 01 '21 at 04:35
  • Are you using selectors(reselect library)? if not you can do the sorting in mapStateToProps – Ravi Theja May 01 '21 at 04:38
  • 1
    I don't think you need Redux. Just call `const allPosts = response.data.articles.sort();` on this line and choose what you want to sort. This is a link to another sort in JS because I do not know what you want to sort by. https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values – NanoBit May 01 '21 at 04:39
  • @NanoBit i want to sort by "load the data as sorted when reading". but the requirement is to do with redux. –  May 01 '21 at 04:43
  • @RaviTheja No i'm not using reselect library. You mean to say i should do the sorting using react? but the requirement is to do it in Redux –  May 01 '21 at 04:45
  • @alex, If you want to stored a sorted object, then you should use redux, else sorting while displaying is fine when you do not to use it elsewhere. – Niraj Patel May 01 '21 at 04:47
  • Then do it in the reducer while storing the data itself. But the requirement of sorting while reading does not apply then. it will be stored as sorted – Ravi Theja May 01 '21 at 04:47
  • 1
    @alex, Does Post comes from your backend? If so, then it is the best practice to send the sorted response from backend itself. – Niraj Patel May 01 '21 at 04:48
  • @NirajPatel how can i store a sorted object using redux? The Post comes from API. How to send the sorted response from api using redux? –  May 01 '21 at 05:00
  • @RaviTheja How can i store as sorted using redux. Any suggestions please –  May 01 '21 at 05:01
  • @alex, Can you share sample response of post ? So contributors can help you in implementing the sorting logic – Niraj Patel May 01 '21 at 05:03
  • @NirajPatel have shared the post.js could you please scroll down the code its below HomePage.js –  May 01 '21 at 05:04

2 Answers2

0

UPDATE: It is not necessarily to use redux to sort an element. Redux is use for state management. You can refer a tutorial link mentioned below. It contains in depth explanation of redux: https://chriscourses.com/blog/redux

NOTE: As suggested in comment, It is best practice to get the sorted response from backend itself.

Although if you still want to sort your response in frontend. Assuming that you get following kind of response:

const allPosts = [
  {
    title: 'Charming Post',
    author: 'Brian',
    description: 'Lorem ipsum etc etc'
  },
  {
    title: 'Amazing Post',
    author: 'Chadwick',
    description: 'Lorem ipsum etc etc'
  },
  {
    title: 'Boring Post',
    author: 'Alex',
    description: 'Lorem ipsum etc etc'
  },
];

Before storing posts in redux, i.e. In Your HomePage.js inside AllPosts function (API call) you can sort your response before storing it (setPosts() function call) as follows:

// by title
const newPostsByTitle = allPosts.sort((a, b) =>  a.title.localeCompare(b.title));

//by author
const newPostsByAuthor = allPosts.sort((a, b) =>  a.author.localeCompare(b.author));

console.log('sorted by title', newPostsByTitle);
console.log('sorted by author', newPostsByAuthor);

then you can store sorted response as follows:

setPosts(newPostsByTitle); // for sorted by title

setPosts(newPostsByAuthor); // for sorted by author
Niraj Patel
  • 810
  • 8
  • 15
  • Thanks Niraj. I will implement it accordingly. –  May 01 '21 at 05:31
  • what should i be importing from react-redux? –  May 01 '21 at 06:58
  • Nothing to import as you are using ```setPosts()``` function, pass that sorted data in that function. – Niraj Patel May 01 '21 at 07:05
  • oh i see, it seems like you are not aware about ```react-redux```. Well for that you can follow below tutorial, it is in details explanation of how you can implement it using redux: https://chriscourses.com/blog/redux – Niraj Patel May 01 '21 at 07:08
  • Thanks. But how can i render the sorted objects to the screen. I'm sorry i have a basic knowledge of redux. –  May 01 '21 at 07:16
  • You just have to pass your variable that contains sorted data into ```setPosts()``` function. – Niraj Patel May 01 '21 at 07:18
  • I have posted in the answer section based on your suggestion to implement. Though everything is in AllPosts variable i'm unable to see any changes rendered on the screen i see its being sorted out in the console.log –  May 01 '21 at 07:39
  • Should i be making any changes in the post.js as well? –  May 01 '21 at 07:40
0
  const AllPosts = () => {
        axios
          .get(`${url}`, { headers: config })
    
          .then((response) => {
            const allPosts = response.data.articles;
            const newPostsByTitle = allPosts.sort((a, b) =>
              a.title.localeCompare(b.title)
            );
            const newPostsByAuthor = allPosts.sort((a, b) =>
              a.author.localeCompare(b.author)
            );
            const newPostsByurlToImage = allPosts.sort((a, b) =>
              a.urlToImage.localeCompare(b.urlToImage)
            );
            const newPostsByDescription = allPosts.sort((a, b) =>
              a.description.localeCompare(b.description)
            );
    
            console.log("sorted by title", newPostsByTitle);
            console.log("sorted by author", newPostsByAuthor);
            console.log("sorted by image", newPostsByurlToImage);
            console.log("sorted by description", newPostsByDescription);
            console.log(response);
            setPosts(allPosts);
            setPosts(newPostsByTitle);
            setPosts(newPostsByAuthor);
            setPosts(newPostsByurlToImage);
            setPosts(newPostsByDescription);
          })
          .catch((error) => console.error(`Error: ${error}`));
      };

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