One of the basic things you need to know when working with React is how to transfer and deal with data from one component to another.
Let's start with some definitions before we go on further.
- What is State?
The state is data that has the ability to change due to a user's actions. Data in state could be added, deleted, or completely overwritten by a user's action.
- What are props?
we use props to pass data between components. we send props down to child components.
- What Is Lifting State?
When implementing state we need to figure out where is going to be.
The best place for this is a parent component from which we can send data to the child components that will need the same state. This is What we call lifting state.
- What Is Inverse Data Flow?
We know we can send data down through props but how could we do the inverse?
well. We simply pass down a callback function and call it in the child component with the data.
- What is CRUD?
Each of the words stands for something.
- C : Create,
- R : Read,
- U: Update,
- D: Delete.
Each represents different operations/interactions we can make to a database.
Get Request
To make a request to a server or an API we can use something called fetch.
When we are dealing with data on react we usually set this data to state.
let's say we have a fetch get request :
useEffect(()=>{
fetch("http://localhost:8000/data")
.then (response => response.json())
.then( data=>{ setData(data)})
},[])
fetch returns a promise. A promise is a representation of an asynchronous calculation.
We see before the last line that we send data to State. This will keep our data deposit for easy retrieval.
What's the next thing from here On Out?
once we get State we can send data to any child component in need of it since we are lifting state.
return(<Child data={data}/>)
Let's also set up a function so we can retrieve data from another child component
function handleChildData(formData){
setData(formData)
}
<SecondChid OnParent={handleChildData} />
This way we could implement inverse data flow. The second child sends data up to the parent.
Our second child happens to be a controlled form :
function SecondChild({onParent}){
const [name,setName]= useState("")
const [email,setEmail] = useState("")
const [date,setDate] = useState(“”)
const [img,setImg] = useState(“”)
function handleSubmit(e){
e.preventDefault()
const formData ={
name: name,
email: email,
date: date,
img: img
}
onParent(formData)
}
<form onSubmit={handleSubmit}>
<div>
<input type="text" name="name" value={name} onChange=
{e=> setState(e.target.value) } placeholder="Name" />
</div>
<div>
<input type="text" name="email" value={email}onChange=
{e=> setEmail(e.target.value)} placeholder ="Author"/>
</div>
<div>
<input type="text" name="date" value={date} onChange=
{e=>setDate(e.target.value)} placeholder="Date" />
</div>
<div>
<input type="text" name="img" value={img} onChange=
{e=>setImg(e.target.value)}placeholder="Image" />
</div>
<input type="submit" value="Submit" />
</form>
}
The controlled form will keep track of the input value a user inputs and update the assigned State for each of them. Then we can package it in a object and send it up towards the parent component.
Then update State with our child's data.
function handleChildData(formData){
setData(formData)
}
Since we have the data on the parent component we could, as usual, do a POST request so the original data and update it with the new one.
function handleChildData(formData){
fetch("http://localhost:8000/data",{
method: "POST",
headers:
{ "Content-Type": "application/json" },
body: JSON.stringify(formData
)})
.then(r=> r.json())
.then(dat=> setData([...data,dat]))
}}
or perhaps a Patch request
fetch(`http://localhost:8000/data/${item.id}`,{
method:"PATCH",
headers: {
"Content-type": "application/json",
},
body:JSON.stringify(
{
name: “Goes By” + name ,
email: “the email is” + email,
date: date + 1) }
)})
.then(r => r.json())
.then((updatedItem)=> (console.log(updatedItem)));
A Patch request updates or changes some data we already have in the database. Not to be confused with a Post request which adds or creates data unto the database.
We also have a Delete request which will be The D in CRUD. The delete request is to eliminate data on the database:
fetch(`http://localhost:8000/data/${item.id}`, {
method: "DELETE",
})
.then((r) => r.json())
.then(() => onDeleteItem(item));
}
In this article, we have gone over some of the most common practices for handling and transferring data In React. I hope This was found helpful.
RESOURCES:
Flanagan,D.(2020)._JavaScript The Definite Guide: Master the World's Most-Used Programming language.
https://developer.mozilla.org/en-US/.
Top comments (0)