my applicants.js
import React, { useEffect, useState } from "react";
import "./Applicant.css";
import axios from "axios";
import Applicant from "./Applicant";
const URL = "http://localhost:5000/applicants";
const fetchHandler = async () => {
return await axios.get(URL).then((res) => res.data);
};
const Applicants = () => {
const [applicants, setApplicant] = useState();
useEffect(() => {
fetchHandler().then((data) => setApplicant(data.applicants));
}, []);
console.log(applicants);
return (
<div>
<ul>
{applicants &&
applicants.map((applicant, i) => (
<li key={i}>
<Applicant applicant={applicant} />
</li>
))}
</ul>
</div>
);
};
export default Applicants;
In the console the output is: undefined applicants.js
there is no other error in the console only this one. i'm using react v6
useEffect is working as compomentDidMount with [] (that means passing without any dependency) and you are trying to print before its running at that time state is undefined
setState()
runs asynchronously in a queue based system. Therefore if you want to update a state, this update will be piled up on the system queue.
However, you can check if data has been loaded
const [applicants, setApplicant] = useState();
useEffect(() => {
fetchHandler().then((data) =>
const newApplicants = data.applicants
setApplicant(data.applicants));
console.log(newApplicants) // returns data
console.log(applicants) // returns undefined but in the final state it will contain the data
}, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.