skip to Main Content

I was building a react application and I used the following code to get data from an API.

import './App.css';
import {useEffect, useState} from 'react';

function App() {
  const [records, setRecords] = useState([]);

  useEffect(()=>{
    getData();
  }, []);

  const getData = async() => {
    const response = await fetch('https://localhost:7280/api/Student/GetAll')
    const recdata = await response.json
    setRecords(recdata["data"])
  }

  return (console.log(records));
}

export default App;

When I check the Network calls the API returns following response

{
"data": [
    {
        "id": 1,
        "firstName": "Harinda",
        "lastName": "Vithana",
        "email": "[email protected]",
        "telephone": "0744896164",
        "nic": "199400560123"
    },
    {
        "id": 3,
        "firstName": "John",
        "lastName": "Cena",
        "email": "[email protected]",
        "telephone": "077164164",
        "nic": "78452123545"
    }
],
"success": true,
"message": ""

}

But in the console it outputs the following result instead of data from the response
enter image description here

I am new to React so I have no idea what’s causing the issue or if this is the correct method to get data. Apologies if I’m missing something obvious.

2

Answers


  1. Your code looks fine. But a small syntax error.

    const getData = async() => {
        const response = await fetch('https://localhost:7280/api/Student/GetAll')
        const recdata = await response.json() // Corrected here 
      //const recdata = await response.json // Previously
        setRecords(recdata["data"])
      }
    

    Happy Coding!

    Login or Signup to reply.
  2. .json is a function for fetch API. So, it will be response.json() over response.json.

    So, the getData() method will be,

      const getData = async() => {
        const response = await fetch('https://localhost:7280/api/Student/GetAll');
        const recdata = await response.json();
        setRecords(recdata["data"]);
      }
    

    Thank you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search