I’m new to react and api consume, we are working with services of our own api for a college project, we have this get method in the service being use by one of the page components
export const getProductCostumer = async (costumerid, state) => {
let data = await api
.get(`ProductCostumer?costumerid=${costumerid}`)
.then((result) => result.data);
state(data);
return data;
};
When the page loads, it says that the state in the get method is undefined despite being set on the component that is being used
const [data, setData] = useState([]);
const Params = useParams();
const showAlert = (id) => {
swal({
title: "Delete",
text: "Are you sure you want to delete this?",
icon: "warning",
buttons: ["Cancel", "Confirm"],
}).then((answer) => {
if (answer) {
deleteProductCostumer(id);
swal({
title: 'Deleted',
text: 'Price has been deleted',
icon: 'success',
}).then(function () { window.location.reload() });
}
});
};
useEffect(() => {
const fetchData = async () => {
try {
const response = await getProductCostumer(Params.costumerid, setData);
setData(response);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, [Params.costumerid]);
Previously the same undefined error happened with the costumerid but it got solved using Params, what could be the case for state being undefined? Apologies for poor grammar
Tried changing the useEffect with the same results trying to get past the state undefined
useEffect(() => {
const fetchData = async () => {
try {
const response = await getProductCostumer(Params.costumerid, setData);
const responseData = response.data;
console.log(responseData);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, [Params.costumerid]);
2
Answers
There are a couple of nonsense things in your first snippet:
that’s a function, which returns the useful data. Then, why pass as argument a callback to set the same data?
you correctly prefixed the api call with
await
. However, you later use the then. You should choose to useasync
/await
or the callback-style, not together.Let’s adjust the code:
I leave to you to review the rest of the code.
It’s a bit hard to understand what you’re asking. You’re actually casting
setData
as a variablestate
(casting a verb as a noun), and calling it twice.Overall, I can’t really tell what you’re asking or what the problem is. I would recommend using Cursor or some other AI-enabled IDE to help you with understanding the code
It might be worth making sure the entire component function isn’t being re-created. You want react to keep calling the same function, and it uses the order of the hooks to keep all of the data persistent