# API

[View on Github](https://github.com/CartoDB/carto-react-template)

{% hint style="warning" %}
**Note:** We are reducing our investment in CARTO for React and currently we discourage users from starting new projects with it.

CARTO for React is an opinionated framework with pre-built components and templates. This greatly speeds up the process to create React-based applications, but customization options are limited.

If you need further customization in React, or you want to build geospatial applications using **Vue, Angular, or any other Javascript-based framework**, we recommend going directly to the main CARTO for Developers documentation, including [CARTO + deck.gl](https://github.com/CartoDB/gitbook-documentation/blob/master/carto-for-developers/key-concepts/carto-for-deck.gl), which allows for maximum flexibility and scalability.
{% endhint %}

| Package          | Version                                                                                                                       | Downloads                                                                                                                        |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| @carto/react-api | [![version](https://img.shields.io/npm/v/@carto/react-api.svg?style=flat-square)](https://npmjs.org/package/@carto/react-api) | [![downloads](https://img.shields.io/npm/dt/@carto/react-api.svg?style=flat-square)](https://npmjs.org/package/@carto/react-api) |

Set of functions that allow to work with CARTO APIs.

## Functions <a href="#functions" id="functions"></a>

### **executeSQL**

Async function that executes a SQL query against [CARTO SQL API](https://api-docs.carto.com/#95aa64ca-128c-4c2c-b156-aa417260050e)

* **Input**:

  Receives a single `Object` argument with the following properties:

| Param                   | Type                               | Description                                                                                                                                                |
| ----------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| credentials             | `Object`                           | CARTO user credentials (check the parameters [here](https://github.com/visgl/deck.gl/blob/v8.9.36/docs/api-reference/carto/overview.md#carto-credentials)) |
| credentials.apiVersion  | `string`                           | SQL API version                                                                                                                                            |
| credentials.username    | `string`                           | CARTO username (required for CARTO 2)                                                                                                                      |
| credentials.apiKey      | `string`                           | CARTO API Key (required for CARTO 2)                                                                                                                       |
| credentials.apiBaseUrl  | `string`                           | API Base URL (required for CARTO 3)                                                                                                                        |
| credentials.accessToken | `string`                           | Access token (required for CARTO 3)                                                                                                                        |
| query                   | `string`                           | SQL query to be executed                                                                                                                                   |
| connection              | `string`                           | Connection name (required for CARTO 3)                                                                                                                     |
| opts                    | `Object`                           | Optional. Additional options for the HTTP request, following the [Request](https://developer.mozilla.org/es/docs/Web/API/Request) interface                |
| opts.abortController    | `AbortController`                  | To cancel the network request using [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)                                    |
| opts.format             | `string`                           | Output format to be passed to SQL API (i.e. ‘geojson’)                                                                                                     |
| queryParameters         | `QueryParameters (@deck.gl/carto)` | Optional. SQL query parameters                                                                                                                             |

* **Returns**: `Object` - Data returned from the SQL query execution
* **Example**:

```jsx
import { executeSQL } from "@carto/react-api";

const credentials = {
  username: "public",
  apiKey: "default_public"
};
const query = `SELECT COUNT(cartodb_id) FROM populated_places`;

const fetchData = async () => {
  const result = await executeSQL({credentials, query});
  return result;
};

const rows = await fetchData();
console.log(rows[0]); // {count: 7343}
```

### **useCartoLayerProps**

React hook that allows a more powerful use of CARTO deck.gl layers, creating a set of layer props (see [@deck.gl/carto module](https://github.com/visgl/deck.gl/blob/v8.9.36/docs/api-reference/carto/overview.md)). It manages automatically filtering and viewport-related calculations, for common use cases.

* **Input**:

| Param                                    | Type                               | Default | Description                                                                                                                                                                  |
| ---------------------------------------- | ---------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| props                                    | `Object`                           |         | { source, \[layerConfig], \[uniqueIdProperty], \[viewportFeatures], \[viewportFeaturesDebounceTimeout]}                                                                      |
| props.source                             | `Object`                           |         | { id, type, connection, data, \[credentials] }                                                                                                                               |
| props.source.id                          | `string`                           |         | Unique source ID.                                                                                                                                                            |
| props.source.type                        | `string`                           |         | Source type. Check available types [here](https://docs.carto.com/deck-gl/reference#type-string)                                                                              |
| props.source.connection                  | `string`                           |         | Connection name. Required only for CARTO 3.                                                                                                                                  |
| props.source.data                        | `string`                           |         | Table name, tileset name or SQL query.                                                                                                                                       |
| props.source.queryParameters             | `QueryParameters (@deck.gl/carto)` |         | SQL query parameters                                                                                                                                                         |
| \[props.source.credentials]              | `object`                           |         | (optional) Credentials for accessing the source (check the object props [here](https://docs.carto.com/development-tools/carto-for-deck.gl/reference#setdefaultcredentials)). |
| \[props.layerConfig]                     | `Object`                           |         | (optional) { id, opacity, visible }                                                                                                                                          |
| \[props.layerConfig.id]                  | `string`                           |         | (optional) Unique layer ID.                                                                                                                                                  |
| \[props.layerConfig.opacity]             | `number`                           | `1`     | (optional) Initial layer opacity.                                                                                                                                            |
| \[props.layerConfig.visible]             | `boolean`                          | `true`  | (optional) Indicates whether the layer is visible by default or not.                                                                                                         |
| \[props.uniqueIdProperty]                | `string`                           |         | (optional) Name of the column for identifying features uniquely. See note below.                                                                                             |
| \[props.viewportFeatures]                | `boolean`                          | `true`  | (optional) Whether to calculate viewport features for this layer or not.                                                                                                     |
| \[props.viewportFeaturesDebounceTimeout] | `number`                           | `250`   | (optional) Timeout for calculating viewport features when there’s a change. It’s used to avoid repeated viewport calculations in a short amount of time.                     |

{% hint style="info" %}
About `uniqueIdProperty`: the uniqueIdProperty allows to identify a feature uniquely. When using tiles, it allows to detect portions of a same feature present in different tiles (think about a road segment crossing 2 tiles) and apply correct calculations (eg. avoid counting the same feature more than once). These are the rules used internally, in this precise order:

1. if user indicates a particular property, it will be honoured.
2. if `cartodb_id` is present, it will be used (all features coming from a `CartoLayer` with Maps API version v2 have this field, just be sure to include it in the SQL you use)
3. if `geoid` is present, it will be used. Some datasets with `MAP_TYPES.TILESET` type have this identifier.
4. finally, if a value isn’t set for this param and none `cartodb_id` or `geoid` are found, every feature (or portion of a feature), will be treated as a unique feature.
   {% endhint %}

* **Returns**: a set of props for the layer.

| Param                               | Type               | Description                                                                                                                                                                                                                    |
| ----------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| props                               | `Object`           | Default props required for layers                                                                                                                                                                                              |
| props.binary                        | `boolean`          | Returns true. The internal viewportFeatures calculation requires MVT property set to true                                                                                                                                      |
| props.uniqueIdProperty              | `string`           | Returns same unique id property for the layer as the input one                                                                                                                                                                 |
| props.type                          | `string`           | Source type. Check available types [here](https://docs.carto.com/deck-gl/reference#type-string)                                                                                                                                |
| props.connection                    | `string`           | Connection name. Used only for CARTO 3.                                                                                                                                                                                        |
| props.data                          | `string`           | Table name, tileset name or SQL query                                                                                                                                                                                          |
| props.credentials                   | `string`           | Credentials for accessing the source                                                                                                                                                                                           |
| props.onViewportLoad                | `function`         | Function that is called when all tiles in the current viewport are loaded. Available when using vector tile sources. Vector tiles are returned if using Maps API v2, or if using Maps API v3 with `MAP_TYPES.TILESET` sources. |
| props.onDataLoad                    | `function`         | Function that is called when all the dataset features are loaded. Available when using Maps API v3 with `MAP_TYPES.TABLE` or `MAP_TYPES.QUERY` sources.                                                                        |
| props.getFilterValue                | `function`         | Accessor to the filterable value of each data object                                                                                                                                                                           |
| props.filterRange                   | `[number, number]` | The \[min, max] bounds of the filter values to display                                                                                                                                                                         |
| props.extensions                    | `[Object]`         | Bonus features to add to the core deck.gl layers                                                                                                                                                                               |
| props.updateTriggers                | `Object`           | Tells deck.gl exactly which attributes need to change, and when                                                                                                                                                                |
| props.updateTriggers.getFilterValue | `Object`           | Updating `getFilterValue` accessor when new filters are applied to source                                                                                                                                                      |

* **Example**

```jsx
import { useCartoLayerProps } from '@carto/react-api';

const cartoLayerProps = useCartoLayerProps(source);

const layer = new CartoLayer({
  ...cartoLayerProps,
  id: 'exampleLayer',
  getFillColor: [255, 0, 255],
}
```
