Query the vehicle list
Routing a vehicle requires a consumption model. Learn how to render a list of vehicles to be able to select the right consumption model.
View on Github
Requirements
- Chargetrip API key - to fetch all vehicles instead of a subset.
- A Mapbox API key - to display the map
- URQL - a lightweight graphQL client
Steps to take
- Use the
vehicleList
query to retrieve a list of vehicles. GraphQL will allow for only fetching the fields that are needed. The filter and search argument can be used to improve the way of how to look up vehicles. Use the page and size argument to implement pagination. To improve performance even more, the thumbnail image of the vehicle is used. - After fetching the data, an
intersectionObserver
needs to be implemented to support endless scroll pagination. - With everything set up, it's time to render the list of vehicles alongside the filters and search onto the screen.
Next steps
With the vehicleList
up and running, it's possible to retrieve additional vehicle details. This will be explained in our next example.
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
/* eslint-disable max-len */
import { createClient, defaultExchanges } from '@urql/core';
import { groupVehicles } from './interface';
import { vehicleListQuery } from './queries';
/**
* For the purpose of this example we use urgl - lightweights GraphQL client.
* To establish a connection with Chargetrip GraphQL API you need to have an API key.
* The key in this example is a public one and gives an access only to a part of our extensive database.
* You need a registered `x-client-id` to access the full database.
* Read more about an authorisation in our documentation (https://docs.chargetrip.com/#authorisation).
*/
const headers = {
'x-client-id': '5ed1175bad06853b3aa1e492',
'x-app-id': '623998b2c35130073829b2d2',
};
const client = createClient({
url: 'https://api.chargetrip.io/graphql',
fetchOptions: {
method: 'POST',
headers,
},
exchanges: [...defaultExchanges],
});
/**
* The function that handles all our GraphQL networking alongside it's parameters.
* @param { Object } - Object that manages the page, size and search to be send towards our request
* @param { number } page - Number of the page we are on
* @param { number } size - Number of vehicles that we should fetch in one request
* @param { string } search - The keywords that we should filter our vehicle list on
*/
export const getVehicleList = ({ page, size = 10, search = '' }) => {
client
.query(vehicleListQuery, { page, size, search })
.toPromise()
.then(response => {
groupVehicles(response.data?.vehicleList);
})
.catch(error => console.log(error));
};