DEV Community

pjparham
pjparham

Posted on

PATCHing nested JSON data in a react application

PATCHing nested JSON data

Working with JSON data can be tricky, and when you are working with nested data it can be even trickier. Let's say that you are working with JSON data for posts on a site and each post has a nested array of comments.

{
  "posts": [
    {
      "id": 1,
      "title": "React 101",
      "subhead": "Some basics to get you started with React",
      "body": "React apps are build using components. These components are used to give you flexibility when writing code.",
      "user": "test",
      "comments": [
        {
          "id": 1,
          "text": "this is really good",
          "username": "Jose Ramirez"
        },
        {
          "id": 2,
          "text": "very helpful!",
          "username": "Jane Smith"
        }
      ]
    },
    {
      "id": 2,
      "title": "Using JSX",
      "subhead": "JSX basics",
      "body": "When writing your markup in react, you write it in JSX. This is very similar to HTML, but with some key differences. One difference to keep in mind is that JSX things expect a prop of className rather than class.",
      "user": "test",
      "comments": [
        {
          "id": 1,
          "text": "This is great.",
          "username": "John Doe"
        },
        {
          "id": 2,
          "text": "Thanks for this!",
          "username": "Kareena Bhatt"
        }
      ]
    },
Enter fullscreen mode Exit fullscreen mode

Your goal is to patch the comments. When working with nested data like this, we can pass in the key of "comments" so the data knows where to go. For the value, we first pass an array that has a value pointing to all the previous comments, then we can pass in our object with the new data. This is what a submit function could look like if you are trying to achieve this:

function onSubmit(e){
        e.preventDefault()
        const newComment = {
            "comments": [
                ...allComments,
                {"text": commentText,
                "id": (commentCountRef.current),
                "username": (user.given_name + " " + user.family_name)}
            ]
        }
        fetch(`http://localhost:3004/posts/${post.id}`, {
            method: "PATCH",
            headers: {
                "Content-Type": "application/json"
        },
        body: JSON.stringify(newComment)
        })
        .then((r) => r.json())
        .then((commentData) => setAllComments(commentData.comments))
        commentCountRef.current += 1
}
Enter fullscreen mode Exit fullscreen mode

You then set your allComments state with all of the comment data. This is because this JSON request returns the entire post object that it fetches.

Utilizing the useRef hook to get id values

When dealing with data like this, another tricky thing is assigning your data the correct ID value. Although there are multiple ways to accomplish this, the useRef hook can be a useful tool and allows you to achieve this without having to import any additional packages. Let's break down how the useRef hook was used in this to assign the correct id value.

Once you have imported the useRef hook to your application and set your current comments to state, you can set the useRef hook to hold the value of the length of your comments array and add one to it, thus equaling what our next id value should be.

    const commentCountRef = useRef(post.comments.length + 1)
Enter fullscreen mode Exit fullscreen mode

As seen above, this is passed into our object as the id. Now you are able to set the id of your new object and set the comments so that both your front-end and back-end technologies are updated when a new comment is submitted.

Top comments (0)