Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add task solution #1150

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 15 additions & 45 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,60 +3,30 @@ import 'bulma/bulma.sass';
import '@fortawesome/fontawesome-free/css/all.css';
import './App.scss';

import classNames from 'classnames';
import { PostsList } from './components/PostsList';
import { PostDetails } from './components/PostDetails';
import { UserSelector } from './components/UserSelector';
import { Loader } from './components/Loader';
import { SharedProvider } from './SharedContext';
import { Sidebar } from './components/Sidebar';
import { MainContent } from './components/MainContent';

export const App: React.FC = () => {
return (
<main className="section">
<div className="container">
<div className="tile is-ancestor">
<div className="tile is-parent">
<div className="tile is-child box is-success">
<div className="block">
<UserSelector />
</div>

<div className="block" data-cy="MainContent">
<p data-cy="NoSelectedUser">No user selected</p>

<Loader />

<div
className="notification is-danger"
data-cy="PostsLoadingError"
>
Something went wrong!
<SharedProvider>
<main className="section">
<div className="container">
<div className="tile is-ancestor">
<div className="tile is-parent">
<div className="tile is-child box is-success">
<div className="block">
<UserSelector />
</div>

<div className="notification is-warning" data-cy="NoPostsYet">
No posts yet
</div>

<PostsList />
<MainContent />
</div>
</div>
</div>

<div
data-cy="Sidebar"
className={classNames(
'tile',
'is-parent',
'is-8-desktop',
'Sidebar',
'Sidebar--open',
)}
>
<div className="tile is-child box is-success ">
<PostDetails />
</div>
<Sidebar />
</div>
</div>
</div>
</main>
</main>
</SharedProvider>
);
};
208 changes: 208 additions & 0 deletions src/SharedContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { SharedContextValue } from './types/ContextValues';
import { getUsers } from './api/users';
import { User } from './types/User';
import { Post } from './types/Post';
import { getPosts } from './api/posts';
import { Comment, CommentData } from './types/Comment';
import { createComment, deleteComment, getComments } from './api/comments';

export const SharedContext = createContext<SharedContextValue | null>(null);

type Props = {
children: React.ReactNode;
};

export const SharedProvider: React.FC<Props> = ({ children }) => {
const [users, setUsers] = useState<User[]>([]);
const [posts, setPosts] = useState<Post[]>([]);
const [comments, setComments] = useState<Comment[]>([]);
const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
const [selectedPostId, setSelectedPostId] = useState<number | null>(null);
const [isLoadingPosts, setIsLoadingPosts] = useState(false);
const [isLoadingComments, setIsLoadingComments] = useState(false);
const [isSumbitting, setIsSumbitting] = useState(false);
const [isError, setIsError] = useState(false);

const handleCreateComment = useCallback(
async ({ name, email, body }: Omit<CommentData, 'postId'>) => {
setIsSumbitting(true);

const trimmedName = name.trim();
const trimmedEmail = email.trim();
const trimmedBody = body.trim();

if (trimmedName && trimmedEmail && trimmedBody && selectedPostId) {
try {
const newComment = await createComment({
postId: selectedPostId,
name: trimmedName,
email: trimmedEmail,
body: trimmedBody,
});

setComments(prevComments => [...prevComments, newComment]);
} catch {
setIsError(true);
} finally {
setIsSumbitting(false);
}
}
},
[selectedPostId, setIsError],
);

const handleDeleteComment = useCallback(
async (commentId: number) => {
try {
await deleteComment(commentId);

setComments(currentComments =>
currentComments.filter(comm => comm.id !== commentId),
);
} catch {
setIsError(true);
}
},
[setIsError],
);

const handleSelectUser = useCallback(
async (userId: number) => {
setSelectedUserId(userId);
setIsLoadingPosts(true);

try {
const loadedPosts = await getPosts(userId);

setPosts(loadedPosts);
} catch {
setIsError(true);
} finally {
setIsLoadingPosts(false);
}
},
[setIsError],
);

const handleSelectPost = useCallback(
async (postId: number) => {
setSelectedPostId(postId);

try {
const loadedUsers = await getUsers();

setUsers(loadedUsers);
} catch {
setIsError(true);
}
},
[setIsError],
);

const handleLoadComments = useCallback(
async (postId: number) => {
setIsLoadingComments(true);
// setIsError(false);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// setIsError(false);


try {
const loadedComments = await getComments(postId);

setComments(loadedComments);
} catch {
setIsError(true);
} finally {
setIsLoadingComments(false);
}
},
[setIsError],
);

const handleClosePostDetails = useCallback(() => {
setSelectedPostId(null);
}, []);

const selectedUser = useMemo(
() => users?.find(user => user.id === selectedUserId) || null,
[users, selectedUserId],
);

const selectedPost = useMemo(
() => posts?.find(post => post.id === selectedPostId) || null,
[posts, selectedPostId],
);

const sharedValue = useMemo(
() => ({
users,
posts,
comments,
isError,
selectedUser,
selectedPost,
isLoadingPosts,
isLoadingComments,
isSumbitting,
handleCreateComment,
handleDeleteComment,
handleLoadComments,
handleSelectUser,
handleSelectPost,
handleClosePostDetails,
}),
[
users,
posts,
comments,
isError,
selectedUser,
selectedPost,
isLoadingPosts,
isLoadingComments,
isSumbitting,
handleCreateComment,
handleDeleteComment,
handleLoadComments,
handleSelectUser,
handleSelectPost,
handleClosePostDetails,
],
);

useEffect(() => {
const fetchUsers = async () => {
try {
const loadedUsers = await getUsers();

setUsers(loadedUsers);
} catch {
setIsError(true);
}
};

fetchUsers();
}, []);

return (
<SharedContext.Provider value={sharedValue}>
{children}
</SharedContext.Provider>
);
};

export const useValues = () => {
const value = useContext(SharedContext);

if (!value) {
throw new Error('Something is wrong with provider SharedContext');
}

return value;
};
14 changes: 14 additions & 0 deletions src/api/comments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Comment, CommentData } from '../types/Comment';
import { client } from '../utils/fetchClient';

export const getComments = (postId: number) => {
return client.get<Comment[]>(`/comments?postId=${postId}`);
};

export const createComment = (comment: CommentData) => {
return client.post<Comment>(`/comments`, comment);
};

export const deleteComment = (commentId: number) => {
return client.delete(`/comments/${commentId}`);
};
6 changes: 6 additions & 0 deletions src/api/posts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Post } from '../types/Post';
import { client } from '../utils/fetchClient';

export const getPosts = (userId: number) => {
return client.get<Post[]>(`/posts?userId=${userId}`);
};
6 changes: 6 additions & 0 deletions src/api/users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { User } from '../types/User';
import { client } from '../utils/fetchClient';

export const getUsers = () => {
return client.get<User[]>(`/users`);
};
19 changes: 19 additions & 0 deletions src/components/CommentsList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react';
import { useValues } from '../SharedContext';
import { CommentsListItem } from './CommentsListItem';

export const CommentsList = React.memo(() => {
const { comments } = useValues();

return (
<>
<p className="title is-4">Comments:</p>

{comments?.map(comment => (
<CommentsListItem key={comment.id} comment={comment} />
))}
</>
);
});

CommentsList.displayName = 'CommentsList';
39 changes: 39 additions & 0 deletions src/components/CommentsListItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from 'react';
import { Comment } from '../types/Comment';
import { useValues } from '../SharedContext';

type Props = {
comment: Comment;
};

export const CommentsListItem: React.FC<Props> = ({ comment }) => {
const { id, name, email, body } = comment;
const { handleDeleteComment } = useValues();

const handleSubmitDeleteComment = () => {
handleDeleteComment(id);
};

return (
<article className="message is-small" data-cy="Comment">
<div className="message-header">
<a href={email} data-cy="CommentAuthor">
{name}
</a>
<button
data-cy="CommentDelete"
type="button"
className="delete is-small"
aria-label="delete"
onClick={handleSubmitDeleteComment}
>
delete button
</button>
</div>

<div className="message-body" data-cy="CommentBody">
{body}
</div>
</article>
);
};
Loading
Loading