Angular Ngrx – Deeply Nested State Update

Merhaba arkadaşlar, uzun bir zaman sonra tekrar aranızda olmaktan dolayı mutluluk duymaktayım. Sizlere naçizane aktarmak istediğim konu Angular Ngrx tarafında bir state içerisinde yer alan değişkenin içerisindeki değişkeni nasıl güncelleyebileceğimize dair bir aktarım yapmak isterim. Aşağıda detayları inceleyebilirsiniz.

BAŞLAMADAN ÖNCE

İç içe yer alan yani state içerisindeki bir değişkenin içerisindeki n değişkeninin yönetilebilirliği daha çok farklı şekilde olabilir. Bu konuyu detaylı araştırmak gerekebilir.

ÖRNEK BİR STATE

export interface PostState {
    showPostId: boolean;
    currentPost: Post;
    currentPostId: number;
    posts: Post[];
    commentPost: Post;
    isNewPost: boolean;
    error: string;
    isNewComment: boolean;
}

const initialState: PostState = {
    showPostId: true,
    currentPost: null,
    currentPostId: null,
    posts: [],
    commentPost: null,
    isNewPost: false,
    error: '',
    isNewComment: false
};

Örnek olarak paylaştığım state içerisinde yer alan posts dizisinin içerisinde property olarak comments adlı bir dizi daha mevcuttur. Örneğin amacımız bir post içerisinde yer alan comment’i güncellemeye çalışalım. Bir post için bir comment eklemeye çalıştığımızda burada Deeply Nested State kavramı ortaya çıkmaktadır.

export class CreateCommentSuccess implements Action {
    readonly type = PostActionTypes.CreateCommentSuccess;

    constructor(public payload: PostComment) { }
}
export function postReducer(state = initialState, action: PostActions): PostState {
    switch (action.type) {

        case PostActionTypes.CreateCommentSuccess:
            const postIndex: number = state.posts.findIndex((item: any) => item.id == action.payload.postId);

            return {
                ...state,
                posts: [
                    ...state.posts.slice(0, postIndex),
                    {
                        ...state.posts[postIndex],
                        comments: [...state.posts[postIndex].comments, action.payload],
                    },
                    ...state.posts.slice(postIndex + 1)
                ],
                error: '',
                isNewComment: false
            };


        default:
            return state;
    }

CreateCommentSuccess action type’da payload’da dönen result’da postId değerini kullanarak var olan state içerisindeki post’u çekiyoruz ve post’un dizi içerisindeki kaçıncı Index’de olduğunu elde ediyoruz.

Elde ettiğimiz Index değeri ile birlikte ilgili post’a comment dizisine bir comment daha ekliyoruz.

YARARLANILAN KAYNAKLAR

https://www.pluralsight.com/guides/deeply-nested-objectives-redux

ÖRNEK

DevPlatform is a platform that meets software developer each other!
https://github.com/dogaanismail/DevPlatform
0 forks.
5 stars.
23 open issues.

Recent commits:

About the author

Add Comment

Bir Cevap Yazın

Blog İstatistikleri

Kategoriler

Arsiv