0

I want to return the number of votes using array.length in ReactJS and display the number of votes

Expected output: Votes: 2

I have a object like this:

"likes" : {
    "like1" : {
      "blogId" : 1,
      "date" : "09-17-2021",
      "id" : "randomID_12345",
      "userId" : "evedave"
    },
    "like2" : {
      "blogId" : 1,
      "date" : "09-17-2021",
      "id" : "randomID_123123",
      "userId" : "evedarryle"
    }
},

NOTE: This is returning as a object but I declare my state as a array Reference : Screenshot of the object

Here's my code:

const blogItems = useSelector((state) => state.blogs);

const [blogData, setBlogData] = useState([]);
const [blogVotes, setBlogVotes] = useState([]);
useEffect(() => {
    setBlogData(blogItems);

    const finalVotesData = blogData.items?.find((blog) => {
      return blog.id === 1;
});

setBlogVotes(finalVotesData?.likes);
}, [blogItems, blogData.items, blogVotes]);
console.log(blogVotes);

Here's the array.length

<p>{blogVotes.length}</p>

How can I display the number of votes using array.length?

  • Why aren't the likes actually stored in an array? – jarmod Sep 17 '21 at 12:07
  • What is the question? – The Fool Sep 17 '21 at 12:09
  • @jarmod Automatically stored as object. I already uploaded the screenshot for the reference. – SPENCER BACAY Sep 17 '21 at 12:12
  • @TheFool Ho can I display the number of votes using array.length? – SPENCER BACAY Sep 17 '21 at 12:12
  • I don't know about your object problem, but you can always use `Object.keys(obj).length`. – The Fool Sep 17 '21 at 12:14
  • It's not an array (but probably should be) so you can't use array.length (obviously). Consider changing the producer of this data to generate an array or otherwise add your own custom length function. – jarmod Sep 17 '21 at 12:14
  • You can declare it as anything you want, but if that's the structure of the data, the likes are being stored as properties, not as elements of the array. You would have to create a `length` property with a getter that gets the number of properties of the `like` property value. – Heretic Monkey Sep 17 '21 at 12:16

1 Answers1

0

Following redux tutorial, seems you can create a new selector to modify blogs. Sorry i don't know if your blogs is same as likes, I'm a bit confused on that.

const blogItemsSelector = createSelector(
  (state) => state.blogs,
  (blogs) => Object.keys(blogs).map(key => ({ key, ...blogs[key] }))
)

After this you can use the new creator,

const blogItems = useSelector(blogItemsSelector)

Here's the tutorial, you might find more stuff useful there, https://react-redux.js.org/api/hooks. Anyway this is an idea. Of course you can go straight to parse data instead of a new selector.

windmaomao
  • 7,120
  • 2
  • 32
  • 36