I am using ReactJS on the front-end to make a POST request to my Djando API. After I make the POST request, I expect for my React component to update itself without me having to refresh the entire page. I’m using a useEffect hook to call the my endpoint(GET) to retrieve the data I just updated.
import React from 'react'
import CampaignList from '../components/CampaignList'
import {useState, useEffect} from 'react'
const campaignRequest = () => {
fetch('http://localhost:8000/api/v1/campaigns/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email_address: "[email protected]",
first_name: "i",
last_name: "k",
stage: "1"
})
})
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error))
}
let Campaigns = () => {
const [recipients, setRecipients] = useState([]);
const [isLoading, setIsLoading] = useState(true);
console.log("Campaign is re-mounted")
useEffect(() => {
setIsLoading(true);
fetch('http://localhost:8000/api/v1/campaigns/')
.then((res) => res.json())
.then((data) => {
setRecipients(data);
setIsLoading(false);
})
.catch(error => console.log(error));
// fetchData()
}
,[]);
if (isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<div>Campaigns</div>
<CampaignList recipientss={recipients}/>
{/* <div>
{recipients.map((recipient, index) => (
<h3 key={index}>{recipient.email_address}
</h3>
))}
</div> */}
<button onClick={campaignRequest}>Click Me</button>
</div>
)
}
export default Campaigns
3
Answers
This is because you do not have anything triggering that get fetch to get called again
put this in your onClick
and this in ur useeffect
I think this should work. Now recipients are updated every time you click.
Looks like you want to
POST
some data tohttp://localhost:8000/api/v1/campaigns/
whenClick Me
is clicked and then automaticallyGET
data from the same URL whenPOST
completes.In your code snippet a
GET
request is located inside of auseEffect
hook with an empty dependencies array, so it will be executed exactly once – on the initial rended.If you want to keep the same code structure, you would have to introduce a new state variable that would trigger the
useEffect
hook –isAddCampaignLoading
for example. You can then moveconst campaignRequest = () => {...}
inside of theCampaigns
component and change theisAddCampaignLoading
state whencampaignRequest
succeeds. Finally, you will addisAddCampaignLoading
to the dependencies array of youruseEffect
hook to make it execute every timeisAddCampaignLoading
changes. I also added a check inside of the hook to make sure campaigns are fetched only whenisAddCampaignLoading
isfalse
(campaignRequest
succeeds).