I have an array called “results
” and it has an array of object. I call a routine in Reactjs
const getdetails = () => {
// api calls
setresults(results);
};
Now when I run another routine for a drop down selection on change, it calls
const handleSelectChange = async (event) => {
console.log(results);
const selectedGuid = event.target.value;
};
The issue is that i need to use the result array and filter all ids that are selectedGuid and then bind to a grid.But the console.log(results)
shows that the results array is empty. Why is the array empty if earlier it had data ? How can i get this to go ?
I have tried to put it in useEffect but not sure if it’s right ?
UPDATE:
This is my api call to get the results.
myService.getDetails(Id).then(function (result) {
// Fetch results
setResults(result);
});
2
The results array is empty because the state update hasn’t propagated by the time you’re logging it.
We can resolve this by using useState() and useEffect() hooks to ensure the results array is set before running handleSelectChange.
I have tried to give example of useEffect() below.
Lets try modify getDetails() as below
const getdetails = async () => {
// api calls
const fetchedResults = await apiCall();
setResults(fetchedResults); // <=== ensure results are updated
};
Lets define useEffect to look for changes in results array
useEffect(() => {
console.log("Updated results:", results);
}, [results]);
Finally let’s update handleSelectChange()
const handleSelectChange = (event) => {
const selectedGuid = event.target.value;
const filteredResults = results.filter(item => item.id === selectedGuid);
console.log(filteredResults);
// bind filteredResults to your grid here
};
Edited and added sample component
const DropDownComponent = () => {
const [results, setResults] = useState([]);
const getdetails = async () => {
try {
const result = await myService.getDetails(Id);
setResults(result);
} catch (error) {
console.error("Error fetching details:", error);
}
};
useEffect(() => {
console.log("Results updated:", results);
}, [results]);
const handleSelectChange = (event) => {
const selectedGuid = event.target.value;
const filteredResults = results.filter(item => item.id === selectedGuid);
console.log("Filtered Results:", filteredResults);
// Bind filteredResults to your grid here
};
return (
<select onChange={handleSelectChange}>
{/* Your options here */}
</select>
);
};
2