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]);
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 use async
/await
or the callback-style, not together.
Let's adjust the code:
export const getProductCostumer = async (costumerid) => {
let result = await api
.get(`ProductCostumer?costumerid=${costumerid}`);
return result.data;
};
I leave to you to review the rest of the code.