Text : Working with RESTful API with Next JS

 This is the code on how to access and interact with an external API. The API is using PHP language and the client is using Next JS.

Part 1.

Client Code:

'use client';

import axios from 'axios';
import { useState } from 'react';

const Home = () => {
  const [msg, setMsg] = useState("");

  const getDataFromAPI = async() => {
    const url = "http://localhost/coc/api/hello.php";
    const response = await axios.get(url,
      {
        params: {
          my_name : 'Makyuz Lanzones'
        }
      }
    );
    setMsg(response.data);
  }

  return (
    <>
      <h1>Working with REST API in Next JS</h1>

      <button onClick={getDataFromAPI}>Get Data</button>
      <h5>{msg}</h5>
    </>
  )
}

export default Home
 
 API CODE:
 
<?php
    header('Content-Type: application/json');
    header("Access-Control-Allow-Origin: *");
   
    $name = $_GET['my_name'];

    echo "Hello $name! This is a message from the API";


  ?>
 

 

 PART 2:

Client Code:

'use client';

import axios from 'axios';
import { useState } from 'react';

const Home = () => {
  const [studentsList, setStudentsList] = useState([]);

  const getDataFromAPI = async() => {
    const url = "http://localhost/coc/api/hello.php";
    const response = await axios.get(url,
      {
        params: {
          yearLevel:'2'
        }
      }
    );

    setStudentsList(response.data);
  }

  return (
    <>
      <h1>Working with REST API in Next JS</h1>

      <button onClick={getDataFromAPI}>Get Data</button>
      <h2>List of Students with Balances</h2>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Balance</th>
          </tr>
        </thead>
        <tbody>
          {
            studentsList.map((student, index) => {
              return (
                <tr key={index}>
                  <td>{student.name}</td>
                  <td>{student.balance}</td>
                </tr>
              )
            })
          }
        </tbody>
      </table>

    </>
  )
}

export default Home

 

 API Code:

<?php
    header('Content-Type: application/json');
    header("Access-Control-Allow-Origin: *");
   
    $yl = $_GET['yearLevel'];

    if($yl == '1'){
      $students = [
        ['name' => 'Boss Marchamz', 'balance'=> '1000'],
        ['name' => 'Bini Mae', 'balance'=> '1200'],
        ['name' => 'Makyuz Lanzones', 'balance'=> '900'],
        ['name' => 'Razzie Baldz', 'balance'=> '100'],
      ];
    }else{
      $students = [
        ['name' => 'Ralph Galz', 'balance'=> '1000'],
        ['name' => 'Princess Mira', 'balance'=> '1200']
      ];
    }

    echo json_encode($students);


  ?>

 

No comments:

Post a Comment

UNITY: USING FIREBALL TO ELIMINATE ENEMIES

 Code user in the video: Fireball Controller using System . Collections ; using System . Collections . Generic ; using UnityEngine ; publ...