Implementing post creation

Now that we have a good grasp on how to request data from an API, we are going to use the useResource Hook for the creation of new data.

Let's get started implementing post creation using the Resource Hook:

  1. Edit src/post/CreatePost.js, and import the useResource Hook:
import { useResource } from 'react-request-hook'
  1. Then, define a new Resource Hook, below the other Hooks, but before our handler function definitions. Here, we set the method to post (creates new data) and we pass the data from the createPost function, to the request config:
    const [ , createPost ] = useResource(({ title, content, author }) => ({
url: '/posts',
method: 'post',
data: { title, content, author }
}))
Here, we are using a shorthand syntax for array destructuring: we are ignoring the first element of the array, by not specifying a value name. Instead of writing const [ post, createPost ], and then not using post, we just put a comma, as follows: const [  , createPost ].
  1. Now, we can use the createPost function in our handleCreate handler function. We make sure that we keep the call to the dispatch function there, so that we immediately insert the new post client-side, while waiting for the server to respond. The added code is highlighted in bold:
    function handleCreate () {
createPost({ title, content, author: user })
dispatch({ type: 'CREATE_POST', title, content, author: user })
}
Please note that, in this simple example, we do not expect, or handle the failure of post creations. In this case, we dispatch the action even before the request completes. However, when implementing login, we are going to handle error states from the request, in order to check whether the user was logged in successfully. It is best practice to always handle error states in real-world applications.
  1. Note that when we insert a post now, the post will first be at the beginning of the list; however, after refreshing, it will be at the end of the list. Unfortunately, our server inserts new posts at the end of the list. Therefore, we are going to reverse the order, after fetching posts from the server. Edit src/App.js, and adjust the following code:
        if (posts && posts.data) {
dispatch({ type: 'FETCH_POSTS', posts: posts.data.reverse() })
}

Now, inserting a new post via the server works fine and we can move on to implementing registration!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.220.114