Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * The application state is a list of Posts and every action is processed by the root reducer, i.e. PostsReducer,
- * which returns the new state.
- */
- function PostsReducer(currentState: Post[] = [], action: Action){
- switch(action.type){
- case 'CREATE_POST':
- return createPost(currentState, action);
- case 'ADD_COMMENT':
- return addCommentToPost(currentState, action);
- default:
- return currentState;
- }
- }
- function createPost(currentState: Post[] = [], action: Action){
- const newPost: Post = {
- id: action.payload.id,
- title: action.payload.title,
- text: action.payload.text,
- createdBy: action.createdBy,
- createdAt: action.createdAt,
- comments: []
- }
- return [...currentState, newPost];
- }
- function addCommentToPost(currentState: Post[] = [], action: Action){
- return currentState.map(post => {
- if(post.id === action.payload.postId) {
- /* this creates a new object copying all atributes in 'post' but replacing
- posts.comments with the result of the commentsRecuder function call.
- */
- return {...post, comments: CommentsReducer(post.comments, action) };
- }else{
- return post;
- }
- });
- }
- function CommentsReducer(currentState: Comment[] = [], action: Action){
- switch(action.type){
- case 'ADD_COMMENT':
- return addComment(currentState, action);
- default:
- return currentState;
- }
- }
- function addComment(currentState: Comment[], action: Action){
- const newComment: Comment = {
- id: action.payload.id,
- text: action.payload.text,
- createdAt: action.createdAt,
- createdBy: action.createdBy
- }
- return [...currentState, newComment];
- }
- interface Post{
- id: string;
- title: string;
- text: string;
- createdBy: string;
- createdAt: number;
- comments: Comment[];
- }
- interface Comment{
- id: string;
- text: string;
- createdBy: string;
- createdAt: number;
- }
- interface Action{
- id: string;
- type: string;
- createdAt: number;
- createdBy: string;
- payload: any; // in a real application create a type for this as well.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement