nxn_404
nxn_404

Reputation: 1

Why my axios get method isn't updating my react useState?

so the code of my app.jsx is

import Navbar from "./components/Navbar";
import TodoList from "./components/TodoList";
import Authentication from "./components/Authentication";
import Sidebar from "./components/Sidebar";
import { useEffect, useState } from "react";
import AccountCenter from "./components/AccountCenter";
import axios from "axios";

function App() {
  // decides if its gonna show the todo list or not
  const [showTodo, setShowTodo] = useState(true);

  // decides if its gonna show the account center or not
  const [showAccCenter, setShowAccCenter] = useState(false);

  // If its true thn shows the signup form and if its false thn shows the login form
  const [signUp, setSignUp] = useState(true);

  // Shows if user logged in or not
  const [loggedIn, setLoggedIn] = useState(false);

  // Save user data
  const [userData, setUserData] = useState({});

  // Function to authenticate
  const checkUserAuth = async () => {
    try {
      // Send a request to the protected route to check if the user is still logged in
      const response = await axios.get(
        "https://doit-rn-backend.onrender.com/api/auth",
        { withCredentials: true },
      );

      // If the response is successful, the user is logged in and the user data is saved
      setUserData(response.data);
      setLoggedIn(true);
    } catch {
      // If authentication fails thn it asks user to login again
      setLoggedIn(false);
      setShowTodo(false);
    }
  };

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

  // Authenticate on page load
  useEffect(() => {
    checkUserAuth();
  }, []);

  // Fetches loggedIn data from localStorage
  useEffect(() => {
    const loggedInData = localStorage.getItem("loggedIn");
    if (loggedInData === "true") {
      setLoggedIn(true);
    } else {
      setLoggedIn(false);
    }
  }, []);

  return (
    <div className="flex h-full w-full flex-col items-center justify-center border-2 border-black bg-[#D6D3C0] sm:h-4/5 sm:w-3/4">
      <Navbar />
      <div className="flex h-full w-full gap-6">
        {loggedIn && (
          <Sidebar
            setShowTodo={setShowTodo}
            setShowAccCenter={setShowAccCenter}
          />
        )}

        {showTodo && <TodoList loggedIn={loggedIn} userData={userData} />}

        {showAccCenter && (
          <AccountCenter
            setLoggedIn={setLoggedIn}
            setSignUp={setSignUp}
            loggedIn={loggedIn}
            showTodo={showTodo}
            userData={userData}
          />
        )}

        {loggedIn === false && (
          <Authentication
            signUp={signUp}
            setSignUp={setSignUp}
            setShowTodo={setShowTodo}
          />
        )}
      </div>
    </div>
  );
}

export default App;

So this code is still under development but as you can see when I fetch data from the backend server and console log the response.data the output is Object { username: "aaaa", userId: "67a5ec5abd38bc1cf6a49c4d" }

but the output of my useEffect clg or when i use console.log(userData) the output is Object { } or blank so why my setUserData(response.data) isnt working? why isnt it updating the useState of userData?

I tried putting the clg after setUserData(response.data); It still showed blank thats why I used the useEffect to clg.

Upvotes: 0

Views: 51

Answers (1)

natashap
natashap

Reputation: 139

The working of states in react is a little bit confusing many a times. The useState hook updates the state variable whose updated value will be available to the component in its next render.

For example, if you do

const [text, setText] = useState("");

setText("text");
console.log(text);

The console.log will print the value of text as an empty string. In the next render you will be able to see "text" in the console.

That being said, try logging the userData just outside useEffect and check if its updating or not.

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

Also check if you are getting the userData in your Todolist component.

Upvotes: 0

Related Questions