React Integration

This document provides instructions on how to use VisitorAPI in React to detect a user’s location, currencies, languages and device info. The information will be stored in states to be used in your React application.

Installing VisitorAPI with NPM

You can install VisitorAPI with NPM with the following command:

npm install visitorapi

Calling VisitorAPI in React

The example code snippet below calls the API.

const VisitorAPI = require("visitorapi");

VisitorAPI("project id").then(data => {
    // handle the return data in json
}).catch(error => {
    // handle error
});

The VisitorAPI function parameters:

The VisitorAPI function will return a promise with the JSON data of the visitor.

Example: Use VisitorAPI to populate state variables

In this example, there are multiple state variables to store the returned data and you can use any of them in your code to control the logic

const VisitorAPI = require("visitorapi");

const [visitorData, setVisitorData] = useState({}); // store the whole json

const [ipAddress, setIpAddress] = useState("");

const [countryCode, setCountryCode] = useState("");
const [countryName, setCountryName] = useState("");
const [state, setState] = useState("");
const [city, setCity] = useState("");
const [cityLatLong, setCityLatLong] = useState(""); // city center latitude and longitude 

const [currencies, setCurrencies] = useState([]); // currencies data is an array
const [languages, setLanguages] = useState([]); // languages data is an array

const [browser, setBrowser] = useState("");
const [browserVersion, setBrowserVersion] = useState("");

const [deviceBrand, setDeviceBrand] = useState("");
const [deviceModel, setDeviceModel] = useState("");
const [deviceFamily, setDeviceFamily] = useState("");

const [os, setOs] = useState("");
const [osVersion, setOsVersion] = useState("");

useEffect(() => {
   VisitorAPI("project id").then(data => {
      setVisitorData(data);
      setIpAddress(data.ipAddress);
      setCountryCode(data.countryCode);
      setCountryName(data.countryName);
      setState(data.region);
      setCity(data.city);
      setCityLatLong(data.cityLatLong);
      setCurrencies(data.currencies);
      setLanguages(data.languages);
      setBrowser(data.browser);
      setBrowserVersion(data.browserVersion);
      setDeviceBrand(data.deviceBrand);
      setDeviceModel(data.deviceModel);
      setDeviceFamily(data.deviceFamily);
      setOs(data.os);
      setOsVersion(data.osVersion);
   }).catch(error => {
      // handle error
   });
},[]);
Still have a question? Contact us
24×7 help from our support staff