Search code examples
reactjsjsonrestcreate-react-app

ReactJs API returns undefined


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": "nagoda@gmail.com",
        "telephone": "0744896164",
        "nic": "199400560123"
    },
    {
        "id": 3,
        "firstName": "John",
        "lastName": "Cena",
        "email": "cenejonah@gmail.com",
        "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.


Solution

  • 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!