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",
    data => {
      // handle the return data in json
    },
    err => {
      // handle error
    }  
);

The VisitorAPI function parameters:

  • Project ID: This is a string that refers to your project in your VisitorAPI projects.
  • Success Handler: This is a function to handle the return data in JSON format when the API is called successfully. For details, please see Visitor Data.
  • Error Handler: This is a function to handle errors.

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",
    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);
    }
  );
},[]);
Still have a question? Contact us
24×7 help from our support staff