jspsych / datapipe

Send data from your behavioral experiments to the OSF. Born-open data as a service.
https://pipe.jspsych.org
MIT License
25 stars 1 forks source link

No condition field provided when calling condition API #91

Open adityac95 opened 9 months ago

adityac95 commented 9 months ago

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.

jodeleeuw commented 9 months ago

Hi @adityac95 ,

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

adityac95 commented 9 months ago

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.