I am using js and jsPsych to code an experiment.
At the end of the task I want to save the data to Firebase Firestore and then redirect to a location. However, currently no data is being saved when I include the window.location.replace. It works fine without the redirection. But I need both. Any advice would be much appreciated.
jsPsych.init({
timeline: timeline,
preload_images: [
on_finish: function() {(saveData(jsPsych.data.get().json()));
(window.location.replace("https://url.com"));
},
});
function saveData(data){
console.log("trying to save");
const db = firebase.firestore();
var data = JSON.parse(data);
var namedData = {};
data.forEach(function(q) {
//console.log(q.internal_node_id)
if(q.hasOwnProperty("responses"))
{
q.responses = JSON.parse(q.responses);
}
namedData[q.internal_node_id] = q;
})
//db.collection("user").doc(subject_id).set(namedData)
db.collection("user").doc(subject_id).set(namedData)
.then(function() {
console.log("data saved")
})
}
Many thanks!
A folks have commented: you are currently redirecting before the data has been saved to the database. To prevent this, you have to wait until the data is saved, for which you can use the then()
that you're currently using to log.
So:
on_finish: function() {
saveData(jsPsych.data.get().json());
},
});
function saveData(data){
console.log("trying to save");
const db = firebase.firestore();
var data = JSON.parse(data);
var namedData = {};
data.forEach(function(q) {
if(q.hasOwnProperty("responses")) {
q.responses = JSON.parse(q.responses);
}
namedData[q.internal_node_id] = q;
})
db.collection("user").doc(subject_id).set(namedData)
.then(function() {
console.log("data saved");
window.location.replace("https://url.com")
})
}
Of if you'd prefer you can return the promise from saveData
and use it in the caller:
on_finish: function() {
saveData(jsPsych.data.get().json()).then(function() {
window.location.replace("https://url.com");
});
},
});
function saveData(data){
console.log("trying to save");
const db = firebase.firestore();
var data = JSON.parse(data);
var namedData = {};
data.forEach(function(q) {
if(q.hasOwnProperty("responses")) {
q.responses = JSON.parse(q.responses);
}
namedData[q.internal_node_id] = q;
})
return db.collection("user").doc(subject_id).set(namedData);
}