Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
August 29, 2023
Apollo in React provides useQuery to fetch GraphQL data and useMutation to execute mutations.
Following is the example of useQuery and useMutation hooks:
import { gql, useQuery, useMutation } from "@apollo/client"; const GET_CARS = gql` query GetCards { cars { id brand } } `; const ADD_CAR = gql` mutation AddCar($brand: String!) { addCar(brand: $brand) { id brand } } `; function Cars({ onCarSelected }) { const { loading, error, data } = useQuery(GET_CARS); const [addCar, otherDetails] = useMutation(ADD_CAR); const inputRef = useRef(); if (loading) return "Loading..."; if (error) return `Error! ${error.message}`; return ( <div> <select name="car" onChange={onCarSelected}> {data.cars.map(({ id, brand }) => ( <option key={id} value={brand}> {brand} </option> ))} </select> <form onSubmit={(e) => { e.preventDefault(); addCar({ variables: { brand: inputRef.current.value } }); // post details related to mutation like { data, loading, error } can be accessed from otherDetails }} > <input ref={inputRef} /> <button type="submit">Add Car</button> </form> </div> ); }