I am new to ReactJs .I'm trying to use the useState hook in react function base component but the value of the state is not getting updated when I am calling the function. I have used that multiple time it was working fine ,but don't know why it is not working now. Please help me out , I am facing this issue since two days.
import React, { useState, useEffect } from 'react'
export default function Home() {
let initialNote = [
{
_id: "",
user: "",
title: "",
description: "",
tag: "",
__v: 0,
},
];
let [data, setData] = useState(initialNote);
const host = "http://localhost:5000/";
const getData = async () => {
const response = await fetch(`${host}notes/fetch`, {
method: "GET", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
headers: {
"Content-Type": "application/json",
// "auth-token": localStorage.getItem("token"),
},
});
const json = await response.json(); // parses JSON response into native JavaScript objects
await setData(json);
// console.log(json);
};
useEffect(
() => {
getData();
console.log(data);
},[]
)
When I consoling the data its giving an empty array.
The fetch api is working fine and if i consoling the json variable so I'm getting the data from the api, but when I am trying to set that data to the setData function it is not updating and I am getting the empty array which I have already declared.
return (
<>
<div className="container">
<form className="m-3">
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">
Email address
</label>
<input
type="email"
className="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
/>
<div id="emailHelp" className="form-text">
We'll never share your email with anyone else.
</div>
</div>
<div className="mb-3">
<label htmlFor="exampleInputPassword1" className="form-label">
Password
</label>
<input
type="password"
className="form-control"
id="exampleInputPassword1"
/>
</div>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
</div>
</>
);
}