Postman works in form data but not in raw or on my server for that matter

So the first piece of code is the backend end point and second is the front end.
It does not send the token to an email address on the server or using Postman raw data.
But it does send a token using form-data. Any ideas I’m new to this. thanks

class RegisterView(View):

    def post(self, request, *args, **kwargs):
        data = request.POST.get('email')
        check_if_email_exists = []
        for email in Registration.objects.all().values_list('email', flat=True):
            check_if_email_exists.append(email)
        if data in check_if_email_exists:
            return JsonResponse('Email already provided', safe=False, status=200)
        else:
            new_user = Registration.objects.create(email=data)
            new_user.save()
            content = {'code': new_user.code}
            send_mail(
                "Thanks for Registering",
                f'Here is your signup Token:{content}',
                '[email protected]',
                [data],
                fail_silently=False,
            )
        return JsonResponse(content, status=201)
const SignUpStep1 = () => {
const navigate = useNavigate();
const [email,setEmail] = useState("");
const dispatch = useDispatch();
const url = "https://motion.propulsion-learn.ch/app/api/auth/registration/";

const updateEmail = (event) => {
    setEmail(event.target.value);
}
const sendVerificationCode = (event) => {
    event.preventDefault();
    if (email.length > 0) {
    const data = {
        email: email
    };
    const fetchConfig = {
        method: 'POST',
        headers: new Headers({
            "Content-Type": "application/json",
        }),
        body: JSON.stringify(data),
    };
    fetch(url,fetchConfig)
    .then((response) => {
    return response.json();
    })
    const action = {
        type:"setEmail",
        payload:email
    };
    dispatch(action)
    navigate("/SignUpStep2")
}else{
    alert("please enter email address");
}

}

Data displayed on server side but is partially undefined at client side

I am trying to fetch data from airtable base and displaying it on client side, the table contains following columns:-

Id, name, formatted_address, cross_street, voting and imageURL.

I am able to display id name image and voting on the client side but formatted_address and cross_street is undefined on the client side but the data is displayed on the server side in Next.js app.

const CoffeeStore = (initialProps) => {
  const router = useRouter();

  const id = router.query.id;

  const [coffeeStore, setCoffeeStore] = useState(initialProps.coffeeStore);

  const {
    state: { coffeeStores },
  } = useContext(StoreContext);

  useEffect(() => {
    if (isEmpty(initialProps.coffeeStore)) {
      if (coffeeStores.length > 0) {
        const coffeeStoreFromContext = coffeeStores.find((coffeeStore) => {
          return coffeeStore.fsq_id.toString() === id; //dynamic id
        });

        if (coffeeStoreFromContext) {
          setCoffeeStore(coffeeStoreFromContext);
        }
      }
    }
  }, [id, initialProps.coffeeStore]);

  const { data, error } = useSWR(`/api/getStoreById?id=${id}`, fetcher);

  useEffect(() => {
    if (data && data.length > 0) {
      console.log("SWR DATA>>>>", data[0]);
      setCoffeeStore(data[0]);
      setVotingCount(data[0].voting);
    }
  }, [data]);

  const {
    name,
    imageURL,
    location: { formatted_address } = "NA",
    location: { cross_street } = "NA",
  } = coffeeStore;

  console.log("COffee STore>>>", coffeeStore);

formatted_address and cross_street is undefined on client side but is displayed on server side.

  console.log(
    id,
    name,
    formatted_address,
    cross_street,
    imageURL
  );
};

export default CoffeeStore;

Google Drive file when upload duplicating same name

When i run a program in google script for upload image from url to drive.program run successful. But i want overwrite the same file in same name not multiple files

This is my code :

function myFunction() {
  var url  ="https://html.com/wp-content/uploads/flamingo.jpg";
  var response = UrlFetchApp.fetch(url);
  console.log(response.getResponseCode());
  var blob=response.getAs('image/jpeg');
  var folder = "1WnbHBPcYd9S4XwXpcYEMX32k********";
  var fileName=decodeURIComponent(url.split("/").pop());
  
  console.log("File named : "+fileName);
  var file=DriveApp.getFolderById(folder).createFile(blob);
  // Set the name to the created file after creating it!
  file.setName("image.jpeg"); 
}

Add item active to carousel using javascript

I have created bootstrap carousel with fetched images from API json. Everything works but I can’t add active item to the first slide and normal item to the rest. I’m still a beginner and any help will be appreciated.

serverInfo = {
  "levelshotsArray": [
    "https://picsum.photos/200",
    "https://picsum.photos/200/300?grayscale", "https://picsum.photos/200"
  ]
}
  
  
  serverInfo.levelshotsArray.map(res => {
  var imge = document.createElement('img');
  imge.src = res;
  imge.height = 100;
  imge.width = 100;
  imge.alt = "";
  document.getElementById('img').appendChild(imge);
  
 
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


<div class="carousel" id="Carousel" data-ride="carousel">
  <ol class="carousel-indicators">
    <li class="active" data-slide-to="0" data-target="#Carousel">
      <li data-slide-to="1" data-target="#Carousel">
  </ol>
  <div class="carousel-inner" role="listbox">
    <div id="img" class="carousel-item active"></div>
    
    
  </div>
</div>

Recharts – Tooltip for individual Bar in a Bar Chart in react

So I have a bar chart having three bars and I wanted to show tooltip for each bar. Currently it shows all bars tooltip as one. Her is my code.

import React, { memo } from "react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  LabelList,
  Rectangle,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { makeStyles } from "@material-ui/core/styles";

import ChartWrapper from "../chartParent/chartWrapper/ChartWrapper";

const Categories = [
  { category: "great", fill: "#00D063" },
  { category: "fair", fill: "#FFC135" },
  { category: "risky", fill: "#F44138" },
];
const useStyles = makeStyles((theme) => ({
  root: {
    margin: -30,
    width: 160,
    backgroundColor: "#fff",
    borderRadius: 5.5,
  },
  title: {
    fontFamily: "Open Sans Condensed",
    fontWeight: 600,
    fontSize: 18,
  },
  tooltipData: {
    width: "100%",
    height: 31,
    borderRadius: "5.5px 5.5px 0px 0px",
  },
  label: {
    color: "#fff",
    fontFamily: "Lato",
    fontWeight: 400,
    fontSize: 14,
    marginLeft: 18,
    paddingTop: "7px",
  },
  toolValue: {
    marginTop: 11,
    marginLeft: 18,
    fontFamily: "Roboto",
    fontWeight: 600,
    fontSize: 19,
  },
  signature: {
    fontWeight: 500,
    fontSize: 14,
    marginTop: -10,
    marginLeft: 18,
    paddingBottom: 11,
    paddingRight: 18,
    color: "#8D8D8D",
    fontFamily: "Lato",
  },
}));
const data = [
  {
    fair: 1,
    great: 1,
    risky: 1,
    week: "5.06 - 11.06",
  },
  {
    fair: 1,
    great: 0,
    risky: 1,
    week: "12.06 - 18.06",
  },

  {
    fair: 1,
    great: 0,
    risky: 1,
    week: "19.06 - 25.06",
  },
  {
    fair: 1,
    great: 1,
    risky: 0,
    week: "26.06 - 2.07",
  },
];

const Categories = [
  { category: "great", fill: "#00D063" },
  { category: "fair", fill: "#FFC135" },
  { category: "risky", fill: "#F44138" },
];
const PerformanceBreakdownChart = () => {
  const classes = useStyles();
  console.log("categories", Categories);

  return (
    <ChartWrapper {...props}>
      <ResponsiveContainer minHeight={150} width={"100%"} height="100%">
        <BarChart
          data={data}
          margin={{
            top: 30,
            right: 20,
            left: 20,
            bottom: 0,
          }}
          barSize={20}
        >
          <CartesianGrid horizontal={false} vertical={false} />
          <XAxis dataKey="week" axisLine={false} tickLine={false} />
          <YAxis hide={true} dy={4} />

          <Tooltip cursor={{ fill: "transparent" }} />
          {Categories.map(({ category, fill }) => (
            <Bar
              key={category}
              dataKey={category}
              fill={fill}
              isAnimationActive={false}
              shape={<Rectangle radius={[10, 10, 10, 10]} />}
              minPointSize={16}
            >
              <LabelList
                dataKey={category}
                position="insideBottomLeft"
                dy={11}
                offset="15"
                angle="-90"
                fill="#FFF"
              />
            </Bar>
          ))}
        </BarChart>
      </ResponsiveContainer>
    </ChartWrapper>
  );
};

export default memo(PerformanceBreakdownChart);

The above code shows tooltip for all bars at once as follows

enter image description here

But, I want to show the tooltip for each individual bar as follows

enter image description here

What can I do to achieve this? Thanks

Passing values from JS to PHP and Echo back HTML

I am studying a code and need help to learn further.

The JS code below is from a Q/A html form that sends data to server.
It crosschecks answer and on server and scores the user.

I need help writing a PHP code that receives the inputs using GET method and echo “ok” back to the html.

JS:

var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function() {
                        if(this.readyState == 4 && this.status == 200) {
                            if(this.responseText == "ok") {
                                document.getElementById("messagefont").innerHTML = checkans;
                                document.getElementById("answer").value = "";
                                document.getElementById('submit-btn').value = continuebutton;
                                checkans.focus();

PHP:

<?php
header('Content-Type: application/json');
$errors = array ();

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' );
if (isset ($_GET['answer'])) {
    $answer = $_GET["answer"];
}
else {
    array_push ($errors, no);
}
$response = "";
if (sizeof ($errors) > 0) {
    $response = implode (",", $errors);
}
else {
$response = ok;
}
echo json_encode($response);
?>

I seem not to be getting something right with the PHP, please i need assistance/guide to fix the PHP code rightly.

How to use bootstrap-vue tables with cell templates

I am using bootstrap-vue, specifically the b-table feature that allows custom data rendering with templates. No matter what I try, I get an error complaining that the data prop for the row is not recognized.

First, without the template, it works as expected (using example code verbatim from the docs)…

Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    fields: [
      { key: 'age', label: 'Old' },
      { key: 'first_name', label: 'Given Name' },
      { key: 'last_name', label: 'Surname' },
    ],
    items: [
      { age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
      { age: 21, first_name: 'Larsen', last_name: 'Shaw' },
      { age: 89, first_name: 'Geneva', last_name: 'Wilson' },
      { age: 38, first_name: 'Jami', last_name: 'Carney' }
    ]
  }
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>

<div id="app">
  <div>
    <b-table striped small :items="items" :fields="fields">    
    </b-table>
  </div>
</div>

Now here, the same thing, except adding a <template> for the one of the columns…

Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    fields: [
      { key: 'age', label: 'Old' },
      { key: 'first_name', label: 'Given Name' },
      { key: 'last_name', label: 'Surname' },
    ],
    items: [
      { age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
      { age: 21, first_name: 'Larsen', last_name: 'Shaw' },
      { age: 89, first_name: 'Geneva', last_name: 'Wilson' },
      { age: 38, first_name: 'Jami', last_name: 'Carney' }
    ]
  }
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>


<div id="app">
  <div>
    <b-table striped small :items="items" :fields="fields">  
    
    <!-- here's the problem: why is "data" not recognized? -->
    <template #cell(name)="data">
        <h3 class="text-info">The AGE IS: {{ data.value.age }}</h3>
        
      </template>
    
    </b-table>
  </div>
</div>

Why isn’t the data prop recognized? I get the error:

[Vue warn]: Property or method “data” is not defined on the instance
but referenced during render.

It’s my understanding that it’s a sort of dummy variable containing the data for the row, and I can call it whatever I like (so long as the code in the template uses the same name). I’ve tried several variations with no luck.

conditional rendering to display in React

enter image description here

I wanted to display badge/text after which condition is met from two conditions.
First condition is that if no openSopts available then show SOLD OUT badge/text and if this condition is not met then check if it is online and then show badge/text of ONLINE.
But badge/text is not shown on card component, can you please tell me what mistake i am doing ?

Display user information with Strapi and react

I take the liberty of contacting you because I am trying to display the user information (after logging in) but I have an error. I think I have to allow this (already checked on strapi) but I don’t know how.

Thanking you in advance

My error : GET http://localhost:1337/api/users/me 401 (Unauthorized)

code : ` const [error, setError] = useState(null);
const [users, setUsers] = useState([]);

useEffect(() => {
  
    axios
      .get('http://localhost:1337/api/users/me')
      
      .then(({ data }) => setUsers(data.data))
      .catch((error) => setError(error))
  }, [])

  


  if (error) {
    // Print errors if any
    return <div>An error occured: {error.message}</div>;
  }`

Dash unselect datatable cell when closing dbc.modal

I am actually working on a dash project. In this one, I have a datatable which is updated each 5 seconds. When I click on a cell of the datatable (= when active_cell is not None), the is_open parameter of my modal is set to true and values depending on the selected cell are pushed to the modal.

Only problem : while the modal is opened, the datas must be automatically actualized depending on the datatable evolution (=datatable is an input in my callback). But the problem is that when I close the modal manually, it will keep opening again and again each time the datatable is updated (because the cell is still active).

So here I come to my question :
How can I unselect the cell when I close the modal ? Because active_cell is an input in the callback so I can’t update it in the same callback. Here is the code of my callback :

@app.callback(Output('graph', 'figure'),
              Output('modal_graph', 'is_open'),
              Input('tbl', 'active_cell'),
              Input('tbl', 'data'),
              )
def update_graphs(active_cell, datatb):
    datas = FundamentalDatas.instance()
    if active_cell and (active_cell['column'] != 0):
        try:
            return datas.create_graph(active_cell, datatb), True
        except Exception:
            raise PreventUpdate
    else:
        raise PreventUpdate

Thanks by advance !

Google Script – Almost perfect, but skipping part of a loop for no apparant reason

I have a fairly long, complicated script I have been working on. It seems to work, however, one of the files to be produced only contains a max. of 2 rows instead of whatever is selected (the other output files are fine). Could anyone take a look and see if I am missing something? Horribly frustrating!

I suspect the script exits the row loop and splits the files before the “MGM” file has been split off from the main file.

Super grateful for any advice or help anyone might have! The rest works fine, so it’s very annoying.

  function checkTrue(selection){
     return selection == "true"
     }
var ss = SpreadsheetApp.getActiveSpreadsheet();
var clientName = ss.getRange("B1").getValue();
var date = Utilities.formatDate(new Date(),"GMT","yyyy-MM-dd" )

function ingestProduct(){
  var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
  var ss = SpreadsheetApp.getActive();
  var selectionRange = ss.getRange("Internal Distributor Information!A:A").getValues();
  var check = selectionRange.some(checkTrue);
 
  var folder = DriveApp.getFolderById("1VftCav6Xi0kfgquSVm1PFMIMa_LQn_6u") //ingestion log folder
  var fugaOrg = ss.getRange("D1").getValue();
  
  var logInfo = ["filler",date,fugaOrg,clientName]
  var fileName = date + " - " + fugaOrg + " " + "(" + clientName + ")"
  if (check === true){
    var copySheet = DriveApp.getFileById("1GuHzDAt9tOhL_rDKXxvxTrCUGpGAeJ8mQZWShoOS74c").makeCopy(fileName, folder);
    var copyID = copySheet.getId();
    var url = copySheet.getUrl();
    logInfo.push(url);
    var logSheet = SpreadsheetApp.openById("1SftHdbfH_vGSN6tgv7GSA-AGaqsAQp6N3231O0H0_Ro").getSheetByName("LOG")
    var Avals = logSheet.getRange("A1:A").getValues();
    var Alast = Avals.filter(String).length+1;
    Logger.log(Alast);
    for(x=1;x<6;x++){
    var editLog = logSheet.getRange(Alast,x).setValue(logInfo[x])
    }
  }

  
  var headers = rows.shift();
  rows.forEach(function(row) { //should shift two rows technically
    if(row[0] === true) {

      var vendor = row[1]
      var label = row[2]
      var catalogNum = row[3]
      var upc = row[4]
      var artist = row[5]
      var title = row[6]
      var primaryGenre = row[7]
      var secondGenre = row[8]
      var format = row[9]
      var units = row[10]
      var formatPack = row[11]
      var length = row[12]
      var width = row[13]
      var height = row[14]
      var weight = row[15]
      var explicit = row[16]
      var releasedate = row[17]
      var presellDate = row[18]
      var narrative = row[19]
      var artwork = row[20]
      var artistbio = row[21]
      var boxlot = row[22]
      var countryManuf = row[23]
      var ppdUsa = row[24]
      var unitsUsa = row[25]
      var ppdUk = row[26]
      var unitsUK = row[27]
      var ppdAus = row[28]
      var unitsAus = row[29]
      var ppdEU = row[30]
      var unitsEU = row[31]
      var tracks = row[32]

      //create Array for each territory

      var usa = ["filler",vendor,label,catalogNum,formatPack,artist,title,upc,"wholesalecost",ppdUsa,releasedate,presellDate,primaryGenre,explicit,boxlot,units,formatPack,unitsUsa,"",tracks]
      var uk = ["filler","labelcode",label,"sublabel",upc,catalogNum,artist,title,artist,title,releasedate,primaryGenre,secondGenre,format,"formatform",units,formatPack,weight,length,width,height,explicit,narrative,ppdUk,"buy price",artwork,"variant"]
      var eu = ["filler",upc,artist,"firstname","lastname",title,"prefix","suffix",label,format,units,boxlot,"language",primaryGenre,releasedate,presellDate,ppdEU,countryManuf,artwork,"album info",artistbio,"composer",formatPack,weight,length+"x"+height+"x"+width]
      var aus = ["filler",label,catalogNum,upc,artist,title,primaryGenre,format,ppdAus,releasedate,narrative,artwork,"audiolink"]

//US
  var destRange = SpreadsheetApp.openById(copyID).getSheetByName("AMPED")
  var Avals = destRange.getRange("A1:A").getValues();
  var Alast = Avals.filter(String).length+1;
  var headerRange = destRange.getRange(1,1,1,30).getValues();
  for(x=1; x < headerRange[0].length;x++){
    destRange.getRange(Alast,x).setValue(usa[x]);
  }

//UK
  var destRange = SpreadsheetApp.openById(copyID).getSheetByName("PROPER")
  var Avals = destRange.getRange("A1:A").getValues();
  var Alast = Avals.filter(String).length+1;
  var headerRange = destRange.getRange(1,1,1,30).getValues();
  for(x=1; x < headerRange[0].length;x++){
    destRange.getRange(Alast,x).setValue(uk[x]);
  }

//EU
  var destRange = SpreadsheetApp.openById(copyID).getSheetByName("BERTUS")
  var Avals = destRange.getRange("A1:A").getValues();
  var Alast = Avals.filter(String).length+1;
  var headerRange = destRange.getRange(1,1,1,30).getValues();
  for(x=1; x < headerRange[0].length;x++){
    destRange.getRange(Alast,x).setValue(eu[x]);
  }
//MGM
  var destRange = SpreadsheetApp.openById(copyID).getSheetByName("MGM")
  var Avals = destRange.getRange("A1:A").getValues();
  var Alast = Avals.filter(String).length+1;
  var headerRange = destRange.getRange(1,1,1,13).getValues();
  for(x=1; x < headerRange[0].length; x++){
    destRange.getRange(Alast,x).setValue(aus[x]);
    Logger.log(aus[x])
  }
  }
  }
  )

  //separate the files
  var distributor = ["AMPED","BERTUS","PROPER","MGM"]
  for (var e = 0; e<distributor.length;e++){
    var destFile = DriveApp.getFilesByName(date + " - " + clientName + " - "+ distributor[e]);
    if (destFile.hasNext() ) //check if file already exists
    {
      Logger.log("File exists");
    }
    else
    {
      //splitting up files
      var ingestionFile = DriveApp.getFileById(copyID).makeCopy(date + " - " + clientName + " - "+ distributor[e],newFolder)
      var ingestionFileID = ingestionFile.getId();
       var ingestionFile2 = DriveApp.getFileById(ingestionFileID);
      var newFolder = DriveApp.getFolderById("1yjKhK-FXpqDUXKuGTjfRhcGSK7djGGIS");
      ingestionFile2.moveTo(newFolder);
      Logger.log(distributor[e])
      if(distributor[e]== "AMPED")
      {
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("PROPER"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("MGM"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("BERTUS"))
      }
      else if(distributor[e]== "BERTUS")
      {
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("PROPER"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("MGM"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("AMPED"))
      }
      else if(distributor[e]== "PROPER")
      {
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("AMPED"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("MGM"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("BERTUS"))
      }
      else if(distributor[e]== "MGM")
      {
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("PROPER"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("AMPED"))
        SpreadsheetApp.openById(ingestionFileID).deleteSheet(SpreadsheetApp.openById(ingestionFileID).getSheetByName("BERTUS"))
      }

    
    }}
     var name = ["name"]
      var email = ["email"]
      var distributor = ["AMPED","PROPER","BERTUS","MGM"]
      for(x=0;x<name.length;x++){
      var file = DriveApp.getFilesByName(date + " - " + clientName + " - "+ distributor[x]);
       if (file.hasNext()) {
         var fileID = file.next().getId()
         var fileUrl = DriveApp.getFileById(fileID).getUrl();
         var filePermission = DriveApp.getFileById(fileID)
         filePermission.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW)
    GmailApp.createDraft(email[x], `New Product: ${clientName} - ${distributor[x]} - ${date}`,
`body`)
}}
    }

How to update values of object in an array of objects

How to update the value of an array text: ‘Dummy data 1’ to ‘Dummy Data’ using setState?

I tried the below code but got an error Cannot assign to read-only property ‘text’ of object ‘#’

const copy = [...updatedDataSource]
copy[0].culturePhrases[4].text = values.text;

0:  phrases: Array(5)
            0: { uid: '4cb9c021', text: 'Dummy data 5'}
            1: { uid: '0f99e2e8', text: 'Dummy data 4'}
            2: { uid: 'efa27b4d', text: 'Dummy data 3'}
            3: { uid: 'fea05b7c', text: 'Dummy data 2'}
            4: { uid: '6f49bd76', text: 'Dummy data 1'}
            length: 5
            [[Prototype]]: Array(0)
        forum_id: "all"
        key: 0
        text: "Our Vision"
        uid: "0e6a9736
        [[Prototype]]: Object
1: {forum_id: 'all', uid: 'e512b8f0', text: 'New Vision', key: 1, phrases: Array(0)}
2: {forum_id: 'all', uid: '6041e7e9', text: 'New Visions', key: 2, phrases: Array(0)}

Tell vite to inline external scripts

I hope I can ask this question somewhat congruently. I am in a situation where my vite production build does not work, but the dev build does.

I am in a statically rendered site, inside a folder site, that then is taken by vite to create the final output. I work mainly in a subfolder _svelte. In there, I also have a folder called api that contains some functions, that I would like to use outside of svelte.

In site, there is another html page, let’s say test/index.html. That page contains a <script type="module">, which then imports these functions from /_svelte/api.

Now, this all works in dev, but in production, the bundle for test/index.html contains references to the script paths, as in /_svelte/api, etc. But these files never exist, so it all fails.

My vite config looks like this:

export default defineConfig(({ command, mode }) => {
  if (command === 'build') {
    // these are all entry files for vite
    const files = fg.sync('**/*.html', {
      cwd: process.env.ROOT,
      absolute: true,
    });

    const external = fg.sync('../_svelte/**/*.ts', {
        cwd: process.env.ROOT,
        absolute: true,
      })
      .map((file) => file.replace(`${__dirname}/site`, ''))
      .filter((file) => !file.includes('main') && !file.includes('vite-env.d.ts'))
      .map((file) => file.replace('.ts', ''));

    return {
      plugins: [svelte({ configFile: '../../svelte.config.js' })],
      root: process.env.ROOT,
      build: {
        publicDir: '../public',
        rollupOptions: {
          input: {
            main: resolve(process.env.ROOT, 'index.html'),
            ...Object.fromEntries(
              files.map((file) => [basename(file.replace('/index', ''), '.html'), file])
            ),
          },
          external,
        },
      },
    };
  }
});

I hope this is enough information somehow to help me in this situation. I am not sure how to fix it, it’s all rather opaque.

How can run a function when content of an element is loaded. Loading more items from a server

I am loading and appending more items from a server to a div. And when they are fully loaded I want to run a function that will refresh colcade layout (reloadColcade).

I have tried adding an event listener to the div with options like ‘load’ and ‘DOMContentLoaded’, divElement.addEventListner('option', reloadColcade) but the event isn’t fired.

And when I try to setTimeout to wait for elements to load either function is invoked too early or too late.

<div class="articles-container grid" data-articles-grid="">
          <div class="grid-col grid-col--1"></div>
          <div class="grid-col grid-col--2"></div>
          <div class="grid-col grid-col--3"></div>

          <% products.forEach(product => { %>
            <% const date = product.createdAt.toISOString().split('T')[0].replaceAll('-', '/'); %> 

            <article class="ver-spacer grid-item" id="<% product._id %>">
              <img src="<%= product.optimizedImgUrl %>" data-original-img-source="<%= product.imgUrl %> " alt="article photo" class="articles-container__article-img">
              <h2><%= product.title %></h2>
              <p><%= product.description %> <button class="articles-container__highlight">Read more</button></p>
              <div class="articles-container__article-info separetor"><p>Price: <%= product.price  %> &#36</p><p>Author: <%= product.authorName %> </p><p>Uploaded: <%= date %></p> <p>Resolution: <%= product.resolution %></p></div>
              <button class="btn-gray articles-container__button ai-c">Add <img src="img/shopping-cart.svg" alt="shopping cart"></button>
          </article>
          <% }); %>
</div>
let colc, colcUploadedByUser, colcPurchasedByUser;
let searchQuery, filter;

const loadMore = async function () {
  let startIndex = 0;

  startIndex += 5;

  const searchQuery = searchForm.querySelector("input").value;
  const filter = searchForm.querySelector("select").value;

  const response = await fetch("load-more", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      startIndex,
      searchQuery,
      filter,
    }),
  });

  const products = await response.json();

  let itemsToAppend = [];

  products.forEach((product) => {
    const date = new Date(product.createdAt)
      .toISOString()
      .split("T")[0]
      .replaceAll("-", "/");

    const htmlString = `
      <img src="${product.optimizedImgUrl}" data-original-img-source="${product.imgUrl}" alt="article photo" class="articles-container__article-img">
      <h2>${product.title}</h2>
      <p>${product.description} <button class="articles-container__highlight">Read more</button></p>
      <div class="articles-container__article-info separetor"><p>Price: ${product.price} &#36</p><p>Author: ${product.authorName} </p><p>Uploaded: ${date}</p> <p>Resolution: ${product.resolution}</p></div>
      <button class="btn-gray articles-container__button ai-c">Add <img src="img/shopping-cart.svg" alt="shopping cart"></button>
      `;

    const item = document.createElement("article");

    item.className = "ver-spacer grid-item";
    item.setAttribute("id", product._id);
    item.insertAdjacentHTML("beforeend", htmlString);

    itemsToAppend.push(item);
  });

  colc.append(itemsToAppend);
};

// Colcade
if (document.querySelector(".grid")) {
  colc = new Colcade(".grid", {
    columns: ".grid-col",
    items: ".grid-item",
  });
}

const reloadColcade = function () {
  colc && colc.layout();
  colcUploadedByUser && colcUploadedByUser.layout();
  colcPurchasedByUser && colcPurchasedByUser.layout();
};