I'm using Redux Toolkit (React native) and the useGetGenreMoviesQuery
hook to fetch movies when the page loads.
const { data, isLoading, error } = useGetGenreMoviesQuery(page);
Now, I want to trigger the same API call when a button is pressed. However, when I tried to destructure the useGetGenreMoviesQuery
hook for the button press:
const [getMovies, { data, isLoading, error }] = useGetGenreMoviesQuery(page);
I got the error:
'TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.'
How can I properly make the API call with a button press in this scenario?
I tried removing the const array and tried to call the same API using refetch from the redux toolkit.
const { data, isLoading, error, refetch } = useGetGenreMoviesQuery(page);
But it is not working.
I have to make the API call again on a user interaction
I believe the refetch
function should work in this case, but the more conventional way to effect a query call as a result of some UI event or in a callback is to use a Lazy Query. The lazy query hooks do return an array containing the trigger function and results.
Export the generated useLazyGetGenreMoviesQuery
hook from your API slice and call the trigger function in the button's onClick
callback handler.
...
const [
getMovies,
{ data, isLoading, error }
] = useLazyGetGenreMoviesQuery();
...
const clickHandler = async (page) => {
try {
const result = await getMovies(page).unwrap();
// success, any additional logic
} catch(error) {
// failure
}
}
...
<button type="button" onClick={clickHandler}>
Get Movies
</button>
...