In this video we are going to add the Create functionality to our React CRUD application. The real heavy lifting here will be done by POST
'ing to our API, so here we will only be concerned with creating and displaying a form using React, and then handling the submit
functionality.
How to Fetch data using React Hooks. In version 16.8.0 React added some new function called React Hooks. Hooks allow you to use state and other React features without writing a class. Hooks are functions that let you 'hook into' React state and lifecycle features from function components. Create React Fetch - GET, PUT, POST, and Delete requests using Hooks and State objects. Use Function-based component and Class-based component techniques to call HTTP methods. Simple GET request using fetch. This sends an HTTP GET request from React to the npm api to search for all react packages using the query q=react, then assigns the total returned in the response to the component state property totalReactPackages so it can be displayed in the render method. Powerful & Configurable. React Query is configurable down to each observer instance of a query with knobs and options to fit every use-case. It comes wired up with dedicated devtools, infinite-loading APIs, and first class mutation tools that make updating your data a breeze.
As we added React router to our app in the previous video, I am going to start by creating a new route for handling creation of new blog posts:
In case it's not immediately obvious, the new line here is:
And the associated import
statement:
import Create from './containers/create';
Ok, so far, so good. We've added a route and told it to display the Create
component when we hit that route. But that component doesn't actually exist, so let's add that also:
All I have done here is copy / paste the form from the Twig implementation and change up a few things.
Firstly, React will have a benny if you use the for
attribute on a label
- so I have changed for
to htmlFor
.
Likewise, React also wants you to use className
instead of class
- for any CSS references.
I've also removed the method='post'
from the form element. The reasoning for this is that this form isn't going to POST
directly - we will handle this ourselves. Also, we don't have an action
in our form
element, for the same reason.
This does raise a question though - if our form is to do something when we click submit
, what should it do?
Wavesfactory cassette 1 0 0. Well, the interesting thing is - that depends :)
In our Create
work flow, we might want to add a little flash message, redirect the user to the list view, and of course, actually send in the POST
request to add the new content.
However, in our Update
work flow, we might want a different flash message, we maybe don't want to redirect the user anywhere - just show the updated page - and this time we would need to make either a PUT
or a PATCH
request.
Fortunately, React makes this easy for us.
Handling Form Submissions
As mentioned, depending on which 'screen' we are on, depends on what should happen when the form is submitted.
In the case of our 'Create' screen we want to POST
off the form's data to the API, and then ideally, redirect the user to the List view. Redirecting is outside the scope of this video, so for now, we will just content ourselves with the POST
'ing of data.
To do this, whereever we use the form, we are going to pass the form an as-yet-unrun function (a callback) that will only be called / run whenever the submit
button is pressed.
The way we will set this up is to tell the form
which function we want to run by way of the onSubmit
function:
React Fetch Post Json
becomes:
There's two important things happening here:
First, we haven't actually created the handleSubmit
function yet, we will do that in a moment.
Second, we are passing in the function itself, not the outcome of running this function - note, no ()
brackets at the end:
onSubmit={this.handleSubmit}
- thisonSubmit={this.handleSubmit()}
- not this
That's really important. In JavaScript you can pass un-run functions around just like you do with any other type of variable. Pretty awesome. This is because functions are first class in JavaScript.
Defining the handleSubmit
function is simple enough:
And this should work now, in some sense anyway.
The thing is, the output from the console.log
is likely not what you are expecting. You will end up with a SyntheticEvent
, which is a bit confusing.
Unfortunately getting the form data is a little more involved than this. We will sort this out, but for the moment, let's quickly refactor out the form HTML into its own class.
Form Component
We want to be able to re-use the form. By passing in the function to run whenever the form is submitted, we have greatly increased the re-usability of this form component. But as it's currently hardcoded into the create.js
file, it needs extracting to be properly re-usable.
Ok, a few changes here. Nch express invoice plus 7 345.
The easiest one - we removed the
render
function, and all this component containing is a form
, we can remove the div
nest and just return the form
instead. Next, we've switched to React.createClass
, rather than extending component. To the very best of my knowledge, there is no real difference between createClass
and extends Component
, but sometimes you see one or the other, and it's helpful to know about both.
For more on this, I recommend reading this very information blog post by Todd Motto.
The idea here is that we are going to pass in the real implementation to be called on submit
. But we still need to handle the initial triggering of the submit
from this component / class.
As such the process will be:
- Define an
onSubmit
function inside ourCreate
component Create
component renders a newForm
component, passing in theonSubmit
function as aprop
Form
component has its own internalhandleSubmit
method which actually calls theonSubmit
method
It's a little confusing, I admit, but it makes sense the more you use it.
Another reason for doing it this way is that using the SyntheticElement
, we can call e.preventDefault();
, which stops the annoying 'bug' where the browser jumps back to the top of the page on form submit.
We must now update our Create
component to use (import
) this Form
, and also pass in the 'real' implementation of our submission handler to the Form
via props
:
Even so, we still won't be getting sent the expected data when the form is submitted. Let's fix that.
Form State
Dealing with forms is hard. I'd generally recommend you don't bother doing this manually on anything but the most trivial of applications. Instead, I'd recommend using a dedicated form library such as React Forms.
However, we are doing this manually, so we need to start keeping track of our form's state
.
By setting the initial state we can make sure we definitely have 'something' in the component's state when the component first loads. If we don't provide any values (by way of props
) then we set some sensible defaults. However, we will have some values when we come to Update
, so this is a little foresight on our part.
Also, here I have added an onChange
listener to both of the input
fields, and also set their respective values to the current state
, e.g.:
Now, whenever a user types in some data into the form field, it will automatically call the defined function - handleBodyChange
in this case:
Which simply updates the state for the current field.
Now, when the user clicks on the submit
button, the state
is passed back through:
Which should output the JavaScript object in the console log output. Phew, we are nearly there.
Although this is quite a lot of indirection, it is also much more modular than our equivalent Angular code.
Submitting Data To The API
The next problem is that not only do we not have a function to actually POST
data to our API, but that we are also sending data in the form of a JavaScript object, rather than JSON which our API expects.
Adding the createBlogPost
function in is straightforward enough.
We need to make sure we convert the given object to JSON by way of JSON.stringify(data)
, and also to set the Content-Type
to application/json
.
Aside from that, this function is largely similar to the GET
function we created earlier.
Acorn 4 5 5 – bitmap image editor. To tie this all together we need a way to actually use this new createBlogPost
action when the submit
button is pressed:
And that's that.
At this stage we have the working basis of our application. Adding in the Update
functionality is a derivation of what we have already done. Deleting is different entirely.
So long as you are at least somewhat comfortable with what you see here, the rest should come together nicely. If not, I strongly suggest checking out the code and playing around with it. And as always, feel free to ask any questions, or provide feedback, suggestions, and improvements :)
Introduction
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. In this tutorial I will show you how to create new resource via REST API POST request using React JS framework. Here I will use ready made available REST API at https://jsonplaceholder.typicode.com/posts for testing purpose. You can also create and deploy your own service using PHP, Codeigniter or Spring, Jersey etc. and call using React JS framework. Here you will see only HTTP POST example.
Related Posts:
Prerequisites
Knowledge of HTML and JavaScript, https://jsonplaceholder.typicode.com/posts, Create React JS Application
Project Directory
The name of the root project directory is react-rest-api-post. You may delete everything from the src directory.
Controller Class
Create RestController.js file under src directory with below content. Notice that you need to import the required module or component such as import React from 'react'
. I have also declared user array to fill later with REST response data from https://jsonplaceholder.typicode.com/posts.
You may learn about componentDidMount()
here at https://reactjs.org/docs/react-component.html.
The POST URI creates a new resource in the server and returns a response in the below format.
Source code of the REST controller class is given below:
Export the RestController
at the end of the RestController
class so that we can use this class in other modules such as we have used it in below index.js file.
View File
React Fetch Get
Finally create index.js file under src directory to start up the application.
React Fetch Post Example
Here we have called component and writing the output of the POST API response to the div id marked as root.
Open the file src/public/index.html, you will find a div with root id. Update the title in this file as 'React – REST API POST Example'.
Testing the Application
React Fetch Post Parameters
Now execute the command npm start
from command prompt and you will see the response data after creating the new resource in the server from https://jsonplaceholder.typicode.com/posts in browser at http://localhost:3000.
New Resource created in the server as shown below. Id : 101 Title : New title added Body : New body added. Hello body. UserId : 2.
Final result on the browser is shown below in the image:
Source Code
Thanks for reading.