Import useUnleashClient:
You need to import the useUnleashClient hook from @unleash/proxy-client-react.
import React, { useState, useEffect } from 'react';
import { useFlag, useUnleashContext, useUnleashClient } from '@unleash/proxy-client-react'; // ADD useUnleashClient here
import styled, { keyframes, css } from 'styled-components';
Get the Unleash Client Instance:
Inside your UnleashRolloutTester component, get the client instance using useUnleashClient().
const UnleashRolloutTester = () => {
const [testResults, setTestResults] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [currentTestingUser , setCurrentTestingUser ] = useState('');
const [featureFlagName, setFeatureFlagName] = useState('filtering-feature');
const updateContext = useUnleashContext();
const unleashClient = useUnleashClient(); // ADD this line
const currentFlag = useFlag(featureFlagName); // You can keep this for the initial display/setup, but won't use it in the loop
Modify testMultipleUsers function:
Inside the for loop in testMultipleUsers, you'll use unleashClient.isEnabled() with the dynamically updated context.
const testMultipleUsers = async () => {
setIsLoading(true);
setTestResults([]);
const results = [];
for (let i = 0; i < dummyUsers.length; i++) {
const user = dummyUsers[i];
setCurrentTestingUser(user.name);
try {
// Update context for this user
await updateContext({
userId: user.id,
// You can also add custom context properties if your strategies use them:
// accountType: user.accountType, // Uncomment if you have a strategy based on accountType
});
// Small delay to ensure context updates (might not be strictly necessary with await updateContext,
// but good for ensuring the Unleash client has time to process the context change and fetch flags if needed)
await new Promise((resolve) => setTimeout(resolve, 300));
// **THIS IS THE KEY CHANGE:** Use unleashClient.isEnabled() with the current context
const flagEnabled = unleashClient.isEnabled(featureFlagName); // REAL FLAG CHECK
results.push({
...user,
flagEnabled: flagEnabled, // Use the actual flagEnabled status
testTimestamp: new Date().toLocaleTimeString(),
});
} catch (error) {
console.error(`Error testing user ${user.id}:`, error);
results.push({
...user,
flagEnabled: false,
error: true,
testTimestamp: new Date().toLocaleTimeString(),
});
}
}
setTestResults(results);
setCurrentTestingUser('');
setIsLoading(false);
};
Top comments (0)