Seamless API Requests with React Hooks-Part 2
In part 1 we took a look at creating a custom hook called
useEndpoint that allowed us to run a
GET request and access the response data from inside our React component function. We’ll now take a look at how we can send a
POST request from a UI action (in this case, clicking a button) and have React render the result.
To do this we need to make a modification to our earlier
useEndpoint function so that it returns not only the response but also a function that will trigger our request when called. That means we’ll need to maintain another stateful element within our custom hook — namely
req, the request we intend to send.
Instead of passing into
useAsyncEndpoint a request object that
axios understands we will provide it a function that returns a request object when executed. This will allow us to generate different requests for the same endpoint structure.
We can abstract out our API model into functions that return custom hooks (although react-hooks eslint won’t like us for doing so, but it still works fine). We want to define a function that represents a
POST request to the
The only variable we are interested in changing at this endpoint is the
data that is sent along with our request. If you look closely you can see the function component of the return object from
useAsyncEndpoint uses the same parameter signature as the inner function that
useAsyncEndpoint is called with.
That means the
postNewTodo function accepts the same input as the inner function we specified earlier, which is the data provided to the request body.
Finally, a simple JSX structure for our return object, with
createTodo called in the
onClick method of our button, completes our working example!
Let me know your thoughts! What do you think of this pattern for doing asynchronous API requests?