24
loading...
This website collects cookies to deliver better user experience
routes.py
to accept input from the React frontend, then commit the database. We'll add the following lines of code to our routes.py file.@app.route("/add", methods=["POST"], strict_slashes=False)
def add_articles():
title = request.json['title']
body = request.json['body']
article = Articles(
title=title,
body=body
)
db.session.add(article)
db.session.commit()
return article_schema.jsonify(article)
Components
directory. Then we'll add some new files, one to manage our API services and another to display a form to the UI, as well as to handle our interaction with the APIService
, which provides our data to Flask.export default class APIService{
// Insert an article
static InsertArticle(body){
return fetch(`http://localhost:5000/add`,{
'method':'POST',
headers : {
'Content-Type':'application/json'
},
body:JSON.stringify(body)
})
.then(response => response.json())
.catch(error => console.log(error))
}
}
import { useState } from 'react';
import APIService from '../Components/APIService'
useState
hook and the APIService
component, we make them available as seen above.const Form = (props) => {
const [title, setTitle] = useState('')
const [body, setBody] = useState('')
const insertArticle = () =>{
APIService.InsertArticle({title,body})
.then((response) => props.insertedArticle(response))
.catch(error => console.log('error',error))
}
const handleSubmit=(event)=>{
event.preventDefault()
insertArticle()
setTitle('')
setBody('')
}
return (
<div>
// Form
</div>
)}
export default Form;
APIService.InsertArticle()
method.This call takes our article object - from the form submitted by the user, as an argument. The response is then sent as a parameter to a function insertedArticle
that we are yet to create in the later steps inside App.js
.A Parameter is variable in the declaration of function while an argument is the actual value of this variable that gets passed to function.- Stackoverflow
handleSubmit
function, we call insertArticle
and then clear the form fields after submission.<form onSubmit = {handleSubmit} >
<label htmlFor="title" className="form-label">Title</label>
<input
type="text"
className="form-control"
placeholder ="Enter title"
value={title}
onChange={(e)=>setTitle(e.target.value)}
required
/>
<label htmlFor="body" className="form-label">Body</label>
<textarea
className="form-control"
placeholder ="Enter body"
rows='6'
value={body}
onChange={(e)=>setBody(e.target.value)}
required
>
</textarea>
<button
className="btn btn-primary mt-2"
>
Publish article</button>
</form>
// import the component
import Form from './Components/Form'
APIService. InsertArticle()
as a parameter, it's then received on this end. Using the spread operator we will combine the newly created article with the available articles. The update is initiated using the setArticles
method and the result is a list of updated articles
.// update the existing article list
const insertedArticle = (article) =>{
const new_articles = [...articles,article]
setArticles(new_articles)
}
<Form insertedArticle={insertedArticle} />
// define variables for the present state of the form and another to change its state
const [showForm, setShowForm] = useState(false);
...
// toggle between the two states,visible and hidden
const toggleShowForm = () => {
setShowForm(!showForm);
}
...
// Trigger the hide/show method
<button
onClick={toggleShowForm}
className="btn btn-primary"
>
Write an article
<i className="bi bi-pencil-square m-2"></i>
</button>
...
// display the form conditionally
{showForm && (
<Form
insertedArticle={insertedArticle}
/>
)}