Search code examples
javascriptgoogle-apigoogle-api-js-client

How to update spreadsheet values from a variable?


I've created a function with three parameters (the client, the value I'm looking for in a table, the value new value to update), but until know I don't know how to update the cell with the determined value.

So far, I succeeded to look for the value in the table, but I cannot update the final cell with the value in parameter of the function. What is the way to do that?

async function modif(client, id1, id2)
{   
    const gsapi = google.sheets({version:'v4',auth: client });

    for (i = 0; i < 50; i++) 
    {

        const opt1 = {spreadsheetId: 'XXX', range: 'Sheet1!A' + (3+i)};
        let data1 = await gsapi.spreadsheets.values.get(opt1);

        if (parseInt(id1) === parseInt(data1.data.values))
        {                                   
            const opt2 = {
            spreadsheetId: 'xxx', 
            range: 'Sheet1!B' + (3+i), 
            valueInputOption: 'USER_ENTERED', 
            resource:{values : id2}
            };

            let res = await gsapi.spreadsheets.values.update(opt2);
        console.log("modifications OK");
            return;
        }
    }
}

I am supposed to have an updated cell, however instead I receive an error message saying : Invalid value at 'data.values'. Error is at the line resource:{values : id2}

Does anyone know how to solve this little error (I guess), I spent 2 hours on this error yesterday without being able to solve it :(

Thanks a lot in advance for your help,


Solution

  • I finally found out what was the problem... When I looked at the documentation here : https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values, I discovered the parameter "values" is an array of arrays...

    As a result I only had to change my syntax to goes from : resource:{values : id2} to : resource:{values : [[id2]]}

    Cheers,