0

setAcessKeys is not updating the state immediately even though the data is available at that point which I know through the console.log(data) or by passing the array manually. I realized that without useEffect, it renders multiple times and the console.log(accessKeys) returns data from the third run going.

import { useState, useEffect } from "react";
import axios from "axios";
import AccessKey from "./AccessKey";
import { toast } from "react-toastify";
import { useNavigate } from "react-router-dom";
import "./AccessKey.module.css";

const AccessKeys = () => {
  const [accessKeys, setAccessKeys] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    const getAccessKeys = async () => {
      try {
        let token = localStorage.getItem("auth");
        const response = await axios.get(
          "http://localhost:5000/api/keys/user",
          {
            headers: {
              authorization: `Bearer ${token}`,
            },
          }
        );

        const data = response.data;

        console.log(data); // [{...}, {...}]

        setAccessKeys((prevKeys) => [...prevKeys, ...data]);

        console.log(accessKeys); // []
      } catch (error) {
        navigate("/");
        toast.error(error.response.data.message);
      }
    };

    getAccessKeys();
  }, [navigate, accessKeys]);

  return (
    <>
      {accessKeys.length > 0 ? (
        <main>
          {accessKeys.map((accessKey) => (
            <AccessKey key={accessKey._id} acesskey={accessKey} />
          ))}
        </main>
      ) : (
        <h4>You do not have any Access Keys at the moment</h4>
      )}
    </>
  );
};

export default AccessKeys;

0 Answers0