Array of objects with values pass to useQuery in the custom hook and it become empty?

Viewed 571

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, onError) => {
    console.log('before arrow function: ', newEvents); //got values
    return useQuery('add-new-events-query', () => AddNewEvents(newEvents), {
        onSuccess: onSuccess,
        onError: onError,
        enabled: false,
    });
};

// in App.js

const [newEvents, setNewEvents] = useState([]);

const addNewEventsResp = useAddNewEventsData(
    newEvents,
    onSuccessUseAddNewEventsData,
    onErrorUseAddNewEventsData
);

and I call addNewEventsResp.refetch() after populating the newEvents array of object.

1 Answers

I believe this is because you have not passed the newEvents on the function parameter. Can you try this:

export const useAddNewEventsData = (newEvents, onSuccess, onError) => {
console.log('before arrow function: ', newEvents); //got values
return useQuery('add-new-events-query', (newEvents) => AddNewEvents(newEvents), { // here (newEvents) =>
    onSuccess: onSuccess,
    onError: onError,
    enabled: false,
});

};

Related