I’m using React Context to manage job data fetched from an API. However, I’m encountering an inconsistency in the state update within my currentJobsProvider component.
import axios from "axios";
import React, { createContext, useEffect, useState } from "react";
export const currentJobsContext = createContext();
const currentJobsProvider = ({ children }) => {
const [currentJobs, setcurrentJobs] = useState([]);
const options = {
method: 'GET',
url: '/api/search',
};
const fetchcurrentJobs = async () => {
try {
const response = await axios.request(options);
const data = response.data;
console.log(data); // Logs fetched data
setcurrentJobs(data);
console.log(currentJobs); // Logs current state
} catch (error) {
console.error(error);
}
};
useEffect(() => {
fetchcurrentJobs();
}, []);
const values = {
currentJobs,
fetchcurrentJobs,
};
return (
<currentJobsContext.Provider value={currentJobs}>
{children}
</currentJobsContext.Provider>
);
};
export default currentJobsProvider;
Problem:
ProviderCurrentOpenings.jsx:19 (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
ProviderCurrentOpenings.jsx:21 []
currentJobs (state) = empty
Although I’ve used the setter function, why is the currentJobs state showing an empty array in the console?