Redux Normalized State Tree for Posts and Comments

Redux recommends using a normalized application state tree, but I'm not sure if this is the best practice in this case. Suppose in the following case:

  • Everyone Circlehas_many Posts.
  • Everyone Posthas_many Comments.

In the backend database, each model is as follows:

Circle:

{
  _id: '1'
  title: 'BoyBand'
}

Message:

{
  _id: '1',
  circle_id: '1',
  body: "Some Post"
}

Comment:

{
  _id: '1',
  post_id: '1',
  body: "Some Comment"
}

In the application state (the final result of all reducers) in the interface is as follows:

{
  circles: {
    byId: {
      1: {
        title: 'BoyBand'
      }
    },
    allIds: [1]
  },
  posts: {
    byId: {
      1: {
        circle_id: '1',
        body: 'Some Post'
      }
    },
    allIds: [1]
  },
  comments: {
    byId: {
      1: {
        post_id: '1',
        body: 'Some Comment'
      },
    allIds: [1]
  }
}

Now, when I come to CircleView, I remove Circlefrom the backend, which returns all associated with him Postsand Comments.

export const fetchCircle = (title) => (dispatch, getState) => {
  dispatch({
    type: constants.REQUEST_CIRCLE,
    data: { title: title }
  })

  request
    .get(`${API_URL}/circles/${title}`)
    .end((err, res) => {
      if (err) {
        return
      }

      // When you fetch circle from the API, the API returns:
      // {
      //   circle: circleObj,
      //   posts: postsArr,
      //   comments: commentsArr
      // }
      // so it easier for the reducers to consume the data

      dispatch({
        type: constants.RECEIVE_CIRCLE,
        data: (normalize(res.body.circle, schema.circle))
      })
      dispatch({
        type: 'RECEIVE_POSTS',
        data: (normalize(res.body.posts, schema.arrayOfPosts))
      })
      dispatch({
        type: 'RECEIVE_COMMENTS',
        data: (normalize(res.body.comments, schema.arrayOfComments))
      })
    })
}

, , . , Post, , (O (N ^ 2)) , .

{
  circles: {
    byId: {
      1: {
        title: 'BoyBand'
      }
    },
    allIds: [1]
  },
  posts: {
    byId: {
      1: {
        circle_id: '1',
        body: 'Some Post'
        comments: [arrOfComments]
      }
    },
    allIds: [1]
  }
}

, .

Q. ? , ?

+4
2

: , !

?

, .

, , .

  • " "

, , .

  • API

API, API . API, , , DNS , API . API, , .


, , , .

+2

, . . , . / ( postId, commentId). . . . , , ..... . KiSS;)

, , , db . https://docs.mongodb.com/ecosystem/use-cases/storing-comments/

0

Source: https://habr.com/ru/post/1648345/


All Articles