0

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>
      
    </>
  );
}


Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

-1

The function inside the useEffect isn't async (as it shouldn't), so javascript will execute the code inside the useEffect without waiting for getData to finish. Therefore, while getData is busy communicating with server, console.log(data) is executed regardless and output undefined because nothing really is defined.

However, good news is that your state data will be updated as soon the communication with server is finished during the fetch, but the value will only be assigned in the next render.

"Ok great it the value should be assigned, but why I don't see any console log?" you might ask?

That is because your useEffect doesn't have dependency ([] at the end of the useEffect), meaning it will run the code inside it only ONCE.

To gain ability to see the proper value being logged out, you will need

  useEffect(() => {
      console.log(data);
    },[data]
  )

Notice the data in dependency list? It means the block of code inside this useEffect will be executed any time the data is changed.

Hope that helps!

Taiwei Tuan
  • 430
  • 2
  • 12