I'm using Django Rest Framework for API, and React JS for frontend, and I need to increment the count of downloads when the button is clicked. I've done that before in Django, but I have no idea how to do that with React. I tried to send the post request to API to increment the count of downloads, but I got this error: Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
. How to fix it, or maybe there is another way to increment the count of downloads?
Here is the data of API:
{
"id": 3,
"category": {
"id": 11,
"parent": {
"id": 2,
"name": "Name",
"slug": "slug",
"img": "Image",
},
"name": "system",
"slug": null,
"img": ""
},
"title": "Title",
"content": "Content",
"image": "",
"pub_date": "2022-02-02",
"counter": 0, // the count of downloads
"file": "file",
"in_archive": false
}
Do I need to create the state of the count of downloads, or there's another way to do that(maybe it has to be in Django)?
And here's how I'm trying to send the post request:
const SoftwareDetail = ({ match }) => {
const [software, setSoftware] = useState([]);
const [counter, setCounter] = useState(null);
const [file, setFile] = useState(null);
const id = match.params.id;
useEffect(() => {
fetch(`http://127.0.0.1:8000/api/software/${id}/`)
.then(response => response.json())
.then(data => {
setSoftware(data);
setFile(data.file);
setCounter(data.counter);
})
}, [id]);
const onFetchData = () => {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
};
fetch(`http://127.0.0.1:8000/api/software/${id}/`, requestOptions)
.then(response => response.json())
.then(data => {
data.counter = counter // I know this isn't right, but I actually don't know how it has to be
})
}
const handleClick = () => {
window.open(file);
setCounter(counter => counter+1);
useEffect(() => {
onFetchData()
}, [])
}
return (
...
<Download handleClick={handleClick} />
...
);
};
const Download = ({ handleClick }) => {
return (
...
<button id={styles["download-start"]} onClick={handleClick}>
<strong>DOWNLOAD</strong>
<small>FILE SIZE: 130 MB</small>
</button>
...
)
}