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
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
Your code looks fine. But a small syntax error.
Happy Coding!
.json
is a function for fetch API. So, it will beresponse.json()
overresponse.json
.So, the getData() method will be,
Thank you!