Displaying Number of Posts and Users
We also want to display the number of posts created by a user and the number of posts in general. Apart from that, we also want to show the number of users.
For that, we need to create another selector in the posts slice, which selects posts based on author
. Normally selectors cannot take in arguments; however, using the following syntax, we can make a selector which takes in an argument:
export const selectPostsByAuthor = postAuthor => state => {
return state.post.posts.filter(({ author }) => postAuthor === author);
};
We also need to keep track of all the users/authors, and for that, we will need to create a new empty array for storing all the authors and updating the list whenever a new author creates a post. By now, the code should look something like this.
Now that we have the relevant selectors, we can import them into index.js
and display the data!
In the ProfileDetails
, we can use the selector like this:
const posts = useSelector(selectPostsByAuthor(name));
The retrieved data can then be displayed accordingly:
<p>Posts: {posts.length}</p>
Similarly, we can select total posts and authors, and display them in the AppDetails
component. The final code for both components should look something like this.
Following is a sandboxed version of the application:
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 3.45
Displaying Number of Posts and Users
Scorri per mostrare il menu
We also want to display the number of posts created by a user and the number of posts in general. Apart from that, we also want to show the number of users.
For that, we need to create another selector in the posts slice, which selects posts based on author
. Normally selectors cannot take in arguments; however, using the following syntax, we can make a selector which takes in an argument:
export const selectPostsByAuthor = postAuthor => state => {
return state.post.posts.filter(({ author }) => postAuthor === author);
};
We also need to keep track of all the users/authors, and for that, we will need to create a new empty array for storing all the authors and updating the list whenever a new author creates a post. By now, the code should look something like this.
Now that we have the relevant selectors, we can import them into index.js
and display the data!
In the ProfileDetails
, we can use the selector like this:
const posts = useSelector(selectPostsByAuthor(name));
The retrieved data can then be displayed accordingly:
<p>Posts: {posts.length}</p>
Similarly, we can select total posts and authors, and display them in the AppDetails
component. The final code for both components should look something like this.
Following is a sandboxed version of the application:
Grazie per i tuoi commenti!