I'm using React and PHP, and I need it to do something specific. I'm using Axios to send requests to my PHP pages which then changes my database. I need to make an update to my MySQL database that changes the is_logged value from true to false if the user closes the page or the browser. The code to do this is set in the window's beforeunload event. However, the database is never updated. Is what I'm trying to do even possible in React?
Here's my React component code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Viewers from './Viewers';
const Live = ({ match }) => {
window.addEventListener("beforeunload", () => {
axios.get('http://localhost/live-streaming-app/get_viewers.php?=' + token)
.then(response => console.log(response))
})
// Set token from url
const token = match.params.token
//Get the fullname and update logged_in to true
const [fullname, setFullname] = useState("")
useEffect(() => {
axios.get('http://localhost/live-streaming-app/get_user.php?token=' + token)
.then(response => {
setFullname(response.data.fullname)
console.log("Data", response.data)
})
.catch(error => console.log(error))
return () => {
axios.get('http://localhost/live-streaming-app/get_viewers.php?=' + token)
.then(response => console.log(response))
.catch(error => console.log(error))
}
}, [token])
//Jsx for when user is unauthorised
const rejected = (
<div className="container text-center pt-5">
<h1>Rejected Connection</h1>
<p>You are unauthorised to view this page</p>
</div>
)
let my_render = ""
if (fullname && fullname != null) {
my_render = <Viewers fullname={fullname} />
} else {
my_render = rejected
}
return my_render
};
export default Live;
Here is the PHP page that is called:
<?php
require 'connect.php';
$token = $_GET['token'];
$sql = "UPDATE `viewers` SET `logged_in`='false' WHERE `live_token`='{$token}'";
if(mysqli_query($con, $sql)){
http_response_code(201);
}
else {
http_response_code(422);
}
exit;
from How to execute axios code using the window's beforeunload event in React
No comments:
Post a Comment