0

I'm really confused about this one.

This is about saving html canvas drawings to the database. I have two variables:

let canvasesData = [];
let savedCanvasesData = [];

canvasesData contains the new data and savedCanvasesData contains the data which has been saved on the server. The first time this code runs every thing works fine, but when it runs for the second time (or more) then things get strange.

$(document).on('click', '#saveDrawings', function(){
    console.log(canvasesData); // This is identical to canvasesData after the update (3 lines down,) why?
    console.log(savedCanvasesData); // This is identical to canvasesData at the second run, how is this possible?
    canvasesData[currentCanvas] = {'img': canvas.toDataURL('image/jpeg', 1), 'txt': $('#drawingDescr').val()};
    console.log(canvasesData);
    if(!arrayIsEqual(canvasesData, savedCanvasesData)){
        //This doesn't run the second time, because the arrays are identical, which shouldn't be so.
        let toSave = canvasesData;
        data = {'imgs': toSave};
        $.post('/APIUrl', data, function(response){
            // The only explanation I have is that this is the first thing that runs
            //  when the button is pressed. But when I console.log() the following line
            //  it tells me it runs only after the response, like it should.
            savedCanvasesData = canvasesData;
        });
    }
});

Nowhere else do I use the savedCanvasesData array. I do use the canvasesData array in other places but these function are not called in this process, so it can't be changed. I'm really confused as to how this can be updated before the onClick code even runs.

Orry
  • 659
  • 6
  • 21
  • 1
    `savedCanvasesData = canvasesData` you are literally assigning the two variables to be the exact same array, and then seem confused why the arrays are equal... – Niet the Dark Absol Oct 11 '21 at 16:59
  • `let toSave = canvasesData;` you are assigning `toSave` to `canvasesData`. Take a copy instead `let toSave = [...canvasesData]` – ABDULLOKH MUKHAMMADJONOV Oct 11 '21 at 17:03
  • @NiettheDarkAbsol only after the response, before the response they shouldn't be the same since it gets updated: `canvasesData[currentCanvas] = {}`. Before the button is clicked, the user draws in the canvas, making `canvas.toDataURL('image/jpeg', 1)` a different value. – Orry Oct 11 '21 at 17:06
  • @ABDULLOKHMUKHAMMADJONOV I use `toSave` because I'm doing some processing on it, this is the data that should be send to the server, but `savedCanvasesData` should contain all the data, which is in `canvasesData`. I didn't include the processing here since it's not relevant. – Orry Oct 11 '21 at 17:08

0 Answers0