diff --git a/src/experiments/data/actions.js b/src/experiments/data/actions.js index fdf0f0fdd1d..16716d534da 100644 --- a/src/experiments/data/actions.js +++ b/src/experiments/data/actions.js @@ -1,23 +1,51 @@ +/** + * External dependencies + */ +import { apiFetch } from '@wordpress/data-controls'; + /** * Internal dependencies */ 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( window.localStorage.getItem( EXPERIMENT_NAME_PREFIX + experimentName ) ); - const newVariation = - storageItem.variationName === 'control' ? 'treatment' : 'control'; - storageItem.variationName = newVariation; window.localStorage.setItem( EXPERIMENT_NAME_PREFIX + experimentName, 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 { type: TYPES.TOGGLE_EXPERIMENT, diff --git a/src/experiments/index.js b/src/experiments/index.js index 97e110fb908..15fcdad264a 100644 --- a/src/experiments/index.js +++ b/src/experiments/index.js @@ -24,24 +24,32 @@ function Experiments( { experiments, toggleExperiment } ) {
- { experiments.map( ( { name, variation }, index ) => { - return ( -