React Toolbox Integration
This guide will walk you through integrating the DQCToolBox with React websites.
Integration Flow
- You need a
surveyId- This is an identifier for your survey or questionnaire.
- It can be any string that helps you identify the survey (e.g., "Customer Satisfaction Survey", "Survey123", etc.).
- Call the
getDQCRequestId(surveyId)function to get arequestId.- Make sure to call this function only once per survey per user.
- Be careful with multiple calls as it will generate multiple requestIds. This can affect the duplicate check.
- If a user takes the same survey multiple times, you can call it again to get a new requestId. You can expect a isDuplicate: true for the same participantID and the same surveyId.
Store your requestId in your databaseor as a new question in your survey.- For fast integration, you only need to save this requestId. Data will be available later in your DQCO-OP dashboard when sending the transaction data with the requestId.
- If you need to get all the DQC data immediately, you can call the next function after getting the requestId.
- (Optional) Call the
getDQCData(requestId)function to get thetools DQC data.- You can call our API with your
requestIdandAPI keyto get the tools DQC data at any time. - This method will provide you the tools DQC data for the given requestId. The data returned has the format from the JSON Response.
If you want real-time monitoring based on deviceScore , isDuplicate, or any other DQC data field, check the documentation for handling each case. We accept both valid requestIds and the special messages listed below when calling this function or sending transaction data to the dashboard.
- You can call our API with your
Note: The requestId could be a valid requestId (20-character string) or one of these special messages:
Tools Demo
- Interactive Demo step by step
Tools Demo
Note: this is a step by step demo with UI components. Your integration needs to run all these steps in the background to get your requestId or DQC data depending on your integration needs
Survey ID:
Request ID:
Prerequisites
Before starting, ensure you have:
- A React project set up (TypeScript or JavaScript).
Project Structure
Here's how your files should be organized after following this guide:
src/
├── components/
│ └── DQCIntegration.tsx # The integration component
├── utils/
│ └── dqcToolbox.ts # DQC utility functions
└── pages/
└── SurveyPage.tsx # Your survey page using the integration
✅ Quick Start Checklist
Follow these steps in order:
- Get your API key from DQCO-OP platform
- Create
dqcToolbox.tsin yoursrc/utils/folder - Replace
'YOUR_DQC_API_KEY'with your actual API key - Create
DQCIntegration.tsxin yoursrc/components/folder - Update the import path in
DQCIntegration.tsxto match your file structure - Add
<DQCIntegration surveyId="your-survey-id" />to your survey page - Replace
"your-survey-id"with your actual survey identifier (it can be a static string or dynamic value) - Test in browser and check console for "DQC RequestId:" log
- Be careful with multiple calls as it will generate multiple requestIds. This can affect the duplicate check.
📌 Steps to Integrate DQC Toolbox with React
- API Key
Make sure you have your API key from the DQCO-OP platform. If you don't have one, follow these steps to get your API key.
- Create the DQC Toolbox Functions
Create a new file dqcToolbox.ts in your project (e.g., in a utils or services folder):
Note: For production applications, you can store your API configuration in environment variables. However, if this complicates your flow (especially in frameworks like Next.js), you can include the API key directly in your React app as shown above.
- TypeScript
// Replace with your actual API configuration
const API_BASE_URL = 'https://api.dqco-op.com';
const DQC_API_KEY = 'YOUR_DQC_API_KEY';
// Concise integration - only essential fields
interface QualityToolsPayload {
requestId: string;
participantId: string;
dataTrustScore: number;
persona: string;
deviceScore: number;
isDuplicate: boolean;
country: string;
subdivision: string;
surveyId: string;
deviceFailures: string[];
}
interface DQCToolBoxModule {
getIdentityRequestId: (surveyId: string) => Promise<{ requestId: string }>;
}
let toolboxPromise: Promise<DQCToolBoxModule> | null = null;
// Get requestId for a surveyId
export const getDQCRequestId = async (
surveyId: string
): Promise<string | null> => {
if (typeof window === 'undefined') {
throw new Error('getDQCRequestId() must run on the client side');
}
if (!surveyId || surveyId.trim() === '') {
throw new Error('SurveyId is required to get RequestId');
}
const loadToolbox = async (): Promise<DQCToolBoxModule> => {
if (!DQC_API_KEY) throw new Error('DQC API key not provided');
if (!toolboxPromise) {
const DQC_TOOLBOX_URL = `${API_BASE_URL}/tools/toolbox/${DQC_API_KEY}`;
toolboxPromise = import(/* webpackIgnore: true */ DQC_TOOLBOX_URL).then(
(mod: Record<string, unknown>) => {
if (!('DQCToolBox' in mod)) {
throw new Error('DQCToolBox not found in module');
}
return mod.DQCToolBox as DQCToolBoxModule;
}
);
}
return toolboxPromise;
};
try {
const toolbox = await loadToolbox();
const { requestId } = await toolbox.getIdentityRequestId(surveyId);
return requestId;
} catch (error) {
console.error('Error getting DQC request ID:', error);
return null;
}
};
// Get DQC data for a requestId (optional)
export const getDQCData = async (
requestId: string
): Promise<QualityToolsPayload | null> => {
if (!requestId || requestId.trim() === '') {
return null;
}
try {
const response = await fetch(`${API_BASE_URL}/tools/request/${requestId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `apikey ${DQC_API_KEY}`,
},
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = (await response.json()) as QualityToolsPayload;
return data;
} catch (error) {
console.error('Error fetching DQC data:', error);
return null;
}
};
- Create the DQC Integration Component
Create a reusable DQC integration component that handles all the tracking automatically:
import React, { useEffect } from 'react';
import { getDQCRequestId, getDQCData } from './dqcToolbox';
interface DQCIntegrationProps {
surveyId: string;
}
const DQCIntegration: React.FC<DQCIntegrationProps> = ({ surveyId }) => {
useEffect(() => {
const initializeDQC = async () => {
try {
const newRequestId = await getDQCRequestId(surveyId);
console.log('DQC RequestId:', newRequestId); // TODO: remove this log in production
// TODO: Store the requestId in your database or survey system.
// If you want a fast integration you can stop here. Data will be available later in your DQCO-OP dashboard when sending the transaction data with the requestId.
// Optional: Get DQC data - if you want to do real-time checks with isDuplicate or deviceScore values.
if (newRequestId) {
const dqcData = await getDQCData(newRequestId);
console.log('DQC Data:', dqcData); // TODO: remove this log in production
// TODO: Store the DQC data along with your survey results
// you can also use this data for real-time decisions. Keep in mind the special requestId values (e.g., `Request-Blocked`, `Could not process`) if needed
}
} catch (error) {
console.error('Failed to initialize DQC tracking:', error);
}
};
initializeDQC();
}, [surveyId]);
return null; // This component runs in background, no UI needed
};
export default DQCIntegration;
Important Notes:
- Store the requestId: Save the requestId to your database or survey system
- Console logs: Remove all console.log statements in production
- Use in Your Survey Page
Now that you have created the DQCIntegration component, here's how to use it in your survey pages:
Key Principles:
- Use a separate component for DQC integration that runs in the background
- Avoid re-rendering issues by not placing DQC logic inside your main survey component
- The integration only depends on the
surveyIdprop
import React from 'react';
import DQCIntegration from './DQCIntegration';
function SurveyPage() {
const surveyId = 'YourSurveyID'; // use a static value or get it from props/state/url
return (
<div>
<h1>{surveyId}</h1>
<DQCIntegration surveyId={surveyId} />
<YourOriginalSurveyLogic />
</div>
);
}
// Your existing survey component
function YourOriginalSurveyLogic() {
return (
<div>
<h1>Your Survey Logic</h1>
</div>
);
}
export default SurveyPage;
This approach is simple because:
- Drop-in Integration: Just add
<DQCIntegration surveyId={surveyId} />to any survey page - Zero Configuration: The component handles all DQC logic internally
- Background Processing: DQC data is collected and stored automatically
- No Props Drilling: Your existing survey components don't need to change their prop structure
Important Notes:
⚠️ Each component mount creates a new requestId: Every time the DQCIntegration component is mounted, it will generate a new requestId, even for the same surveyId. This allows tracking of multiple visits to the same survey.
⚠️ Component re-renders vs re-mounts: The component only creates a new requestId when it's mounted (not on re-renders). React's useEffect with [surveyId] dependency ensures it runs when the component mounts or when surveyId changes.
⚠️ For single-session tracking: If you want to prevent multiple requestIds for the same survey session, consider implementing session storage logic or move the DQCIntegration component to a higher level in your component tree. This may be needed in integrations like Next.js where the same surveyId is used across multiple pages/questions and needs to unmount/remount.
⚠️ Page refreshes and navigation: If the page is refreshed or the user navigates away and back, a new requestId will be generated. If this is expected in your app (e.g., a Next.js app or survey where you can come back later), to avoid this:
- Consider using
sessionStorageto persist the requestId within the browser session - Or implement a check in your backend to handle page refresh scenarios
- Be aware that this may affect duplicate detection if not handled properly