1

I've a functional react component like this, using Tanstack Query v4 and react 18:

const Userview = (props) => {
...
const userQueries = useQueries({
    queries: props.users.map((user) => {
        return {
            queryKey: ['users', user.id],
            queryFn: () => fetchUserById(user.id),
                {
                    enabled: props.users,
                },
                {
                    headers: {
                        'Content-Type': 'application/json',
                    }
                }),
        },
        {
            onSuccess: (v) => {
                console.log(v)
            },
            onError: (e) => {
                console.log(e)
            },
        }
    }),
})

useEffect(() => {
    if (props.users) {
        console.log(props.users);
    }
}, [props.users])
...
}

How do i execute the queries when props.users is no longer undefined? Now i'm getting the error because of props.users.map() is undefined on first mounting. Is there a correct way, or a "best practice" to do this? I've only found this case for a single useQuery in the docs.

Tobi
  • 73
  • 8
  • 1
    Generally the best practice in cases like this is to have a single `fetchUsers` api call instead of making multiple calls. In which case you would pass in an array of userIds to `fetchUsers`. It is better to aggregate everything into one request and receive one response. – Barry Michael Doyle Apr 25 '23 at 09:44
  • That means no "props.users.map" at all? And "queryKey: ['users', props.users]"? Or how does this work exactly? – Tobi Apr 25 '23 at 10:05

0 Answers0