Update toggleExperiment to support backend experiments

This commit is contained in:
Moon 2022-02-24 12:35:22 -08:00
parent ed9a9fca55
commit 1071ef87eb
2 changed files with 59 additions and 23 deletions

View File

@ -1,23 +1,51 @@
/**
* External dependencies
*/
import { apiFetch } from '@wordpress/data-controls';
/** /**
* Internal dependencies * Internal dependencies
*/ */
import TYPES from './action-types'; import TYPES from './action-types';
import { EXPERIMENT_NAME_PREFIX } from './constants'; import { EXPERIMENT_NAME_PREFIX, TRANSIENT_NAME_PREFIX } from './constants';
export function toggleExperiment( experimentName ) { function toggleFrontendExperiment( experimentName, newVariation ) {
const storageItem = JSON.parse( const storageItem = JSON.parse(
window.localStorage.getItem( EXPERIMENT_NAME_PREFIX + experimentName ) window.localStorage.getItem( EXPERIMENT_NAME_PREFIX + experimentName )
); );
const newVariation =
storageItem.variationName === 'control' ? 'treatment' : 'control';
storageItem.variationName = newVariation; storageItem.variationName = newVariation;
window.localStorage.setItem( window.localStorage.setItem(
EXPERIMENT_NAME_PREFIX + experimentName, EXPERIMENT_NAME_PREFIX + experimentName,
JSON.stringify( storageItem ) JSON.stringify( storageItem )
); );
}
function* toggleBackendExperiment( experimentName, newVariation ) {
try {
const payload = {};
payload[ TRANSIENT_NAME_PREFIX + experimentName ] = newVariation;
yield apiFetch( {
method: 'POST',
path: '/wc-admin/options',
headers: { 'content-type': 'application/json' },
body: JSON.stringify( payload ),
} );
} catch ( error ) {
throw new Error();
}
}
export function* toggleExperiment( experimentName, currentVariation, source ) {
const newVariation =
currentVariation === 'control' ? 'treatment' : 'control';
if ( source === 'frontend' ) {
toggleFrontendExperiment( experimentName, newVariation );
} else {
yield toggleBackendExperiment( experimentName, newVariation );
}
return { return {
type: TYPES.TOGGLE_EXPERIMENT, type: TYPES.TOGGLE_EXPERIMENT,

View File

@ -24,24 +24,32 @@ function Experiments( { experiments, toggleExperiment } ) {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{ experiments.map( ( { name, variation }, index ) => { { experiments.map(
return ( ( { name, variation, source }, index ) => {
<tr key={ index }> return (
<td className="experiment-name">{ name }</td> <tr key={ index }>
<td align="center">{ variation }</td> <td className="experiment-name">
<td align="center"> { name }
<Button </td>
onClick={ () => { <td align="center">{ variation }</td>
toggleExperiment( name ); <td align="center">
} } <Button
isPrimary onClick={ () => {
> toggleExperiment(
Toggle name,
</Button> variation,
</td> source
</tr> );
); } }
} ) } isPrimary
>
Toggle
</Button>
</td>
</tr>
);
}
) }
</tbody> </tbody>
</table> </table>
</div> </div>