datapipe icon indicating copy to clipboard operation
datapipe copied to clipboard

No condition field provided when calling condition API

Open adityac95 opened this issue 2 years ago • 2 comments

This is the provided code to request the next condition number if not using jsPsych:

const response = await fetch("https://pipe.jspsych.org/api/condition/", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "*/*",
  },
  body: JSON.stringify({
    experimentID: "myExpIDHere",
  }),
});

However, though I can get the response, the condition field does not appear to be in the JSON. I keep getting the error "Cannot read properties of undefined" when I use the value response.condition to index into an array of four elements.

adityac95 avatar Nov 29 '23 22:11 adityac95

Hi @adityac95 ,

Can you provide the surrounding context code as well? Is it in an async function?

jodeleeuw avatar Nov 29 '23 23:11 jodeleeuw

Yes. The relevant code is:

const conditionPairs = [
	['note','medium'],
	['short','long'],
	['note', 'long'],
	['short','medium'],
];

let participantMelodies = [];
let participantRatings = [[], []];
let currTrialNum = 0;
let currRatingNum = 0;
let trialConditions;
let currCondition;
let currMelodyToRate = '';
let emailId = '';

// get condition assignment
async function getCondition() {
	const response = await fetch("https://pipe.jspsych.org/api/condition/", {
		method: "POST",
	  	headers: {
	    	"Content-Type": "application/json",
	    	Accept: "*/*",
	  	},
	  	body: JSON.stringify({
	    	experimentID: "myExpIDHere",
	  	}),
	});
	console.log(response);
	return response
}

async function initExperiment() {
    let response;
    try {
        response = await getCondition();
    } catch (error) {
        console.error("Error fetching condition:", error);
        // Fallback to a random condition if fetch fails
        response = { condition: Math.floor(Math.random() * conditionPairs.length) };
    }

    trialConditions = conditionPairs[response.condition];

    // Set up the initial trial
    setupInitialTrial();
}

function setupInitialTrial() {
	// set the condition
    currCondition = trialConditions[currTrialNum];
}

// Call this function to start the experiment
initExperiment();

The TypeError is raised when setupInitialTrial() is called inside the initExperiment() function.

adityac95 avatar Nov 29 '23 23:11 adityac95