I got a question. Hope you can tell me what I'm doing wrong and how to fix it.
I'm trying to pass an array of objects to useQuery in the custom hook.
I did a console log and there are values in the array. But after it went into the function that is calling axios, the array become empty.
Here is the code:
// in the custom hook
const AddNewEvents = async (newEvents) => {
console.log('AddNewEvents fn: ', newEvents); //showing empty array
//return await axios.post(`${process.env.REACT_APP_API_URL}Event`, newEvents);
};
export const useAddNewEventsData = (newEvents, onSuccess, one rror) => {
console.log('before arrow function: ', newEvents); //got values
return useQuery('add-new-events-query', () => AddNewEvents(newEvents), {
onSuccess: onSuccess,
onError: one rror,
enabled: false,
});
};
// in App.js
const [newEvents, setNewEvents] = useState([]);
const addNewEventsResp = useAddNewEventsData(
newEvents,
onSuccessUseAddNewEventsData,
one rrorUseAddNewEventsData
);
and I call addNewEventsResp.refetch() after populating the newEvents array of object.
CodePudding user response:
I believe this is because you have not passed the newEvents on the function parameter. Can you try this:
export const useAddNewEventsData = (newEvents, onSuccess, one rror) => {
console.log('before arrow function: ', newEvents); //got values
return useQuery('add-new-events-query', (newEvents) => AddNewEvents(newEvents), { // here (newEvents) =>
onSuccess: onSuccess,
onError: one rror,
enabled: false,
});
};
CodePudding user response:
The parameters from the inner function shadows the outer function parameters and the variable. You can just access the variables inside the inner function, because when it tries to find a variable, it goes from its scope, if not found goes to the outer scope, in this case the outer function's scope and finds them.
But if you declare parameters in the inner function, they are founded and because you does not pass a value for them, their values are undefined. So you get undefined.
remove them from the inner function
export const useAddNewEventsData = (newEvents, onSuccess, one rror) => {
console.log('before arrow function: ', newEvents); //got values
return useQuery('add-new-events-query', AddNewEvents(newEvents), { // here (newEvents) =>
onSuccess: onSuccess,
onError: one rror,
enabled: false,
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>