Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState } from 'react';
- import { createRoot } from 'react-dom/client';
- import { Provider, useDispatch, useSelector } from 'react-redux';
- import { store } from './app/store';
- import { selectName, setName } from './features/profileSlice';
- import { selectPosts, createPost, selectPostsByAuthor, selectAuthors } from './features/postsSlice';
- import './index.css'
- function ProfileDetails(props) {
- const dispatch = useDispatch();
- const name = useSelector(selectName);
- const posts = useSelector(selectPostsByAuthor(name));
- const [nameField, setNameField] = useState(true);
- return (
- <div className="details">
- <h2>Profile</h2>
- <label htmlFor="name">Name: </label>
- <input
- id="name" value={name} disabled={nameField}
- onChange={(e) => dispatch(setName(e.target.value))}
- />
- <button onClick={() => setNameField(!nameField)}>
- {nameField ? "Change" : "Save"}
- </button>
- <p>Posts: {posts.length}</p>
- </div>
- );
- }
- function AppDetails(props) {
- const posts = useSelector(selectPosts);
- const users = useSelector(selectAuthors);
- return (
- <div className="details">
- <h2>App</h2>
- <p>Users: {users.length}</p>
- <p>Total Posts: {posts.length}</p>
- </div>
- );
- }
- function DetailsSection(props) {
- return (
- <div id="details-section">
- <ProfileDetails />
- <AppDetails />
- </div>
- );
- }
- function CreatePost(props) {
- const dispatch = useDispatch();
- const name = useSelector(selectName);
- const [text, setText] = useState('');
- const handleClick = (e) => {
- e.preventDefault();
- if(text !== '') {
- dispatch(createPost({
- author: name,
- text: text
- }));
- setText('');
- }
- };
- return (
- <div id="create-post">
- <textarea
- id="create-post-textarea"
- value={text}
- onChange={(e) => setText(e.target.value)}
- />
- <button id="create-post-button" onClick={handleClick}>Post</button>
- </div>
- );
- }
- function Posts(props) {
- const posts = useSelector(selectPosts);
- return (
- <div>
- {posts.map((item) =>
- <div key={item.id} className="post">
- <p className="post-text">{item.text}</p>
- <p className="post-author">Posted By: {item.author}</p>
- </div>
- )}
- </div>
- );
- }
- function PostsSection(props) {
- return (
- <div id="posts-section">
- <CreatePost />
- <Posts />
- </div>
- );
- }
- function Main(props) {
- return (
- <div id="main">
- <DetailsSection />
- <PostsSection />
- </div>
- );
- }
- createRoot(document.getElementById('root'))
- .render(
- <React.StrictMode>
- <Provider store={store}>
- <Main />
- </Provider>
- </React.StrictMode>
- );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement