vincent Owen
vincent Owen

Reputation: 9

Post method return Json data keeps on looping

So, I am building a website that tries to first post an id from the front end then on the php file. The post method return a questions that is base on the id that is send to the backend and query through the database. This is my code

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET,POST");
header("Content-Type: application/json; charset=UT-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");


$servername = "localhost";
$username = "root";
$password = "";
$database= "credentials";
 
// Create connection
$db = mysqli_connect($servername, $username, $password, $database);


// Check connection
if ($db->connect_error) {
  die("Connection failed: " . $db->connect_error);
}

$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)){
  $request = json_decode($postdata);
  $quizID = $request->QuizID;
  $sql = "SELECT * FROM question WHERE QuizID='$quizID'";
  $result = mysqli_query($db,$sql);
  if(mysqli_num_rows($result)>0){
    $json_array = array();
    while($row = mysqli_fetch_assoc($result))
    {
      $json_array[] = $row;
    }

    $response = ["data"=>"valid","quiz"=>$json_array];

    echo json_encode($response);
  }else{
    $response = ["data"=>"invalid"];
    echo json_encode($response);
  }
  }    
?>

The front end was successfully return the JSON data but it keeps looping non stop. Why is that happening, I tried running the query first then I store in variable but still it keeps looping.

This is my front end code

useEffect(()=>{
        console.log("use effect");
        const sendData = {
            QuizID: localStorage.getItem("quizID")
        }
        console.log("adad")
        axios.post("http://localhost/pepep/fetchLesson.php", sendData).then(res=>{
            console.log("post success");
            console.log(res.data.quiz[0]);
            setQuestion([res])
        })
    })

Can anyone help me with this ?

Upvotes: 0

Views: 75

Answers (1)

Quentin
Quentin

Reputation: 943981

You have setQuestion([res]) which will set the state to a new value.

Setting the state will trigger a re-render.

Your useEffect call doesn't have a dependency array, so it will run on every render.

Add a dependency array with a list of variables that should trigger the function when they change.

Since you don't appear to be using any external variables, it looks like that should be none.

useEffect( () => { /* ... */ }, [] );

Upvotes: 1

Related Questions