Reputation: 839
I have the following useEffect hook within my react app with useState:
const [jobTypes, setJobTypes] = useState([]);
const getJobTypes = async () => {
try {
const response = await fetch('/job-types');
const jsonData = await response.json();
setJobTypes(jsonData);
const jobTypeName = jobTypes.find(jobType => jobType.ret === jobDetails.jobType)
console.log("jobTypeName: ", jobTypeName)
} catch (err) {
console.error(err.message);
}
}
useEffect(() => {
getJobTypes();
}, []);
The issue I am facing is that I need to wait for setJobTypes(jsonData)
to complete prior to performing my find statement, i.e:
const jobTypeName = jobTypes.find(jobType => jobType.ret === jobDetails.jobType)
as I am getting back an undefined for jobTypeName
Can anyone assist with the best approach to achieve the above as I only want to execute my array.find
when jobTypes
is available
Upvotes: 0
Views: 36
Reputation: 12787
I think the best way is using jsonData
instead of jobTypes
const jobTypeName = jsonData.find(jobType => jobType.ret === jobDetails.jobType)
Upvotes: 2