In the last lecture we fetched some post data and we can render it to the screen by updating our state
but of course, we're fetching too many posts here. Now for a real application,
you probably can send some query parameter to your backend to restrict the amount of data you want
to fetch, some pagination basically.
But of course we can also transform the data once we got it,
so here I'll add a new constant posts,
and now in the then block of componentDidMount and then, I'll assign response data here.
Now I'll call the slice method on that array and only get the elements 1 to 4, to only fetch the first
four posts.
Actually I fetched them all but I only store 4 of them in that post constant, I'll then create a second
constant updatedPosts even, because I want to add an author field to my posts.
Now typically you would of course get this from your backend but our fake backend doesn't have that,
so I simply add here to also show you that of course, you can edit the data you fetch from the server,
we're just working with javascript in the end so we can add any javascript code we want.
So here I will take my posts, call the map method on them and for each post, I want to return a new javascript
object where I distribute the property of the post, so the properties we got from the server basically
and then also add a new author property which I'll hard code to Max. With that, I got the updated posts
now and I'll set the posts to my set state to them.
Now the data we get back from the server was shortened and also transformed in that we added the author field
and that of course is just one example transformation to showcase that you can of course work with
the data you will get back before setting it to the state. With that change in place,
we now got that author field, that also is a field of one output in that post element.
So there I expect to get
author prop,
I can now set this prop in the blog container, here
I can now
also pass this author should be post author, that author field we just added to each object we stored
in the state.
If we save this, we now see the author here and we see only four posts.
This is how you can transform the data, how you can work with the data in componentDidMount
in this example.