How to call one query multiple times with different variable vaules using useQuery or useLazyQuery

Hi, I have an array of objects with ids, i need to get all users data based on ids, i written like below, but i am getting only last id 124 related data. i am unable to get ids 121,122 and 123 data. can any one please help me on how to call an api multiple times with different ids and how to store that all data in local react state

const USER_DATA=gql`
query User($id:String){
      User(id:$id){
            id
            name
            email
            phone
       }}`

const myIds = [
    {id:'121',name:"Kiran"},
    {id:'122',name:"Joshi"},
    {id:'123',name:"Raju"},
    {id:'124',name:"Ravi"},
  ];
function App(){

const [fetchUser, {loading, data, error}] = useLazyQuery(USER_DATA)

useEffect(() => {
    myIds.map(async(item)=>await fetchUser({
      variables: {
       id:item.id
      }
    }))
  }, []);

useEffect(()=>{
console.log(data,'users data...')
},[data])

}
1 Like

Hi! Two suggestions:

  1. Do you have control over the API? Then I would implement an endpoint that can handle multiple IDs, like so:
type Query {
    users(ids: [ID!]!): [User!]!
}
  1. If that is not possible, you might want to try sending a single request with multiple selection sets rather than sending multiple requests, like so:
const myIds = [
    { id:'121', name: 'Kiran' },
    { id:'122', name: 'Joshi' },
    { id:'123', name: 'Raju' },
    { id:'124', name: 'Ravi' },
];
const query = gql`
    query User {
        ${myIds.map(({ id }) => `
            User(id: "${id}") {
                id
                name
                email
                phone
            }
        `}
    }
`;
const { data, loading } = useQuery(query);
2 Likes