React FilePond causes rendering loop when compressing images

I am using React FilePond with the FilePondPluginImageExifOrientation and FilePondPluginImagePreview plugins to handle image uploads in my React application. I added a custom image compression logic using the CompressorJS library in the onprocessfile event. However, I am encountering a rendering loop issue, where the component keeps re-rendering in an infinite loop.

const [files, setFiles] = useState([]);
    const [processingFiles, setProcessingFiles] = useState(false);

    // Function to handle image compression
    const compressImage = file => {
        return new Promise((resolve, reject) => {
            new Compressor(file, {
                quality: 0.8,
                success: compressedResult => {
                    resolve(compressedResult);
                },
                error: error => {
                    reject(error);
                },
            });
        });
    };

    // Handle image compression and upload when files change
    useEffect(() => {
        const handleUpload = async () => {
            try {
                if (processingFiles || files.length === 0) return; // No files to compress or already processing

                setProcessingFiles(true); // Set the flag to indicate we are processing files

                const imageFile = files[0].file;
                const compressedImage = await compressImage(imageFile);

                setFiles([{ file: compressedImage }]); // Set the compressed image as the new file for FilePond

                setProcessingFiles(false); // Reset the flag after processing
            } catch (error) {
                console.error('Error compressing image:', error);
                setProcessingFiles(false); // Reset the flag on error as well
            }
        };

        handleUpload();
    }, [files, processingFiles]);

Any insights or suggestions on how to resolve this rendering loop issue and correctly compress images using React FilePond and CompressorJS would be greatly appreciated. Thank you!

How to handle array Post request to prisma in NextJS

I’m trying to post an array through Prisma to db but with no success

here is my initial data and form validation :

type ModifierFormProps = {
  initialData: {
    modifier: Modifier | null;
    modifierItems: ModifierItem[];
    name?: string;
    price?: number;
    id?: string;
    // modifierPrices: ModifierPrice[];
  };
};

const formSchema = z.object({
  modifierName: z.string().min(1),
  modifierItems: z.array(
    z.object({
      name: z.string().optional().nullable(),
      id: z.string().optional().nullable(),
      price: z.number().optional().nullable(),
    })
  ),

});

and

  const form = useForm<ModifierFormValues>({
    resolver: zodResolver(formSchema),

    defaultValues: initialData
      ? {
          ...initialData,
          modifierItems: [{ name: "", id: "", price: 0.0 }],
          // modifierPrices: [{ price: 0.0, id: "", name: "" }],
        }
      : {
          modifierName: "",
          modifierItems: [{ name: "", id: "", price: 0.0 }],
          // modifierPrices: [{ price: 0.0, id: "", name: "" }],
        },
  });

this is the how I handled the submission :


  const onSubmit = async (data: ModifierFormValues) => {
    try {
      setLoading(true);
      console.log(data);
      if (initialData) {
        await axios.patch(
          `/api/${params.storeId}/modifiers/${params.modifierId}`,
          data
        );
      } else {
        await axios.post(`/api/${params.storeId}/modifiers`, data);
      }

      router.refresh();
      router.push(`/${params.storeId}/modifiers`);
      toast.success(toastMessage);
    } catch (error) {
      toast.error("Check all the field values");
    } finally {
      setLoading(false);
    }
  };

the body console log is like :
,,,
{
modifierName: ‘test’,
modifierItems: [ { name: ‘item 1’, id: ”, price: 1 } ]
}
,,,,

the console log from the form inputs as initial data passed to the post method :

enter image description here

this is what I’ve tried to handle post but the name and price doesn’t get saved in the db and when I get to console log the result of the sent data I get no price or name just the modifierName


export async function POST(
  req: Request,
  {
    params,
  }: {
    params: {
      storeId: string;
    };
  }
) {
  try {
    const { userId } = auth();
    const body = await req.json();

    const {
      modifierName,
      modifierItem,
    }: {
      modifierName: string;
      modifierItem: Array<{ name: string; price: number }>;
    } = body;

    console.log(body);
    if (!userId) {
      return new NextResponse("Unauthenticated", { status: 401 });
    }

    if (!params.storeId) {
      return new NextResponse("Store ID is required", { status: 400 });
    }

    const storeByUserId = await prismadb.store.findFirst({
      where: {
        id: params.storeId,
        userId,
      },
    });

    if (!storeByUserId) {
      return new NextResponse("Unauthorized", { status: 403 });
    }

   
    const modifier = await prismadb.modifier.create({
      data: {
        modifierName,
        storeId: params.storeId,
        ...(modifierItem && {
          modifierItem: {
            createMany: {
              data: {
                name: modifierItem.map((item) => item.name),
                price: modifierItem.map((item) => item.price),
              },
            },
          },
        }),
      },
    });

    return NextResponse.json(modifier);
  } catch (error) {
    console.log("[MODIFIER_POST]", error);
    return new NextResponse("Internal Error", { status: 500 });
  }
}

this is the result of the sent data :

{
id: ‘a12cba53-530a-4cbf-8f39-e66ba193611c’,
modifierName: ‘1’,
name: ”,
createdAt: ‘August 5th , 2023 at 10:21 AM’,
price: 0
}

any one can help ?

I know that and I’m sure that’s I’m making a mistake inside the create method to prisma but I couldn’t figure out how to do it !

Sort data based on multiple fields in javascript

I have a requirement to sort the data and below is what my data looks like.

[
  {
    "id": "course1",
    "type": "course",
    "sequence": 1
  },
  {
    "id": "course2",
    "type": "course",
    "sequence": 2
  },
  {
    "id": "course1_chapter1",
    "type": "chapter",
    "sequence": 1,
    "course": {
      "id": "course1",
      "sequence": 1
    }
  },
  {
    "id": "course1_chapter2",
    "type": "chapter",
    "sequence": 2,
    "course": {
      "id": "course1",
      "sequence": 1
    }
  },
  {
    "id": "course2_chapter1",
    "type": "chapter",
    "sequence": 1,
    "course": {
      "id": "course1",
      "sequence": 2
    }
  },
  {
    "id": "course1_chapter1_lesson1",
    "type": "lesson",
    "sequence": 1,
    "course": {
      "id": "course1",
      "sequence": 1
    },
    "chapter": {
      "id": "chapter1",
      "sequence": 1
    }
  },
  {
    "id": "course1_chapter1_lesson2",
    "type": "lesson",
    "sequence": 2,
    "course": {
      "id": "course1",
      "sequence": 1
    },
    "chapter": {
      "id": "chapter1",
      "sequence": 1
    }
  },
  {
    "id": "course1_chapter2_lesson1",
    "type": "lesson",
    "sequence": 1,
    "course": {
      "id": "course1",
      "sequence": 1
    },
    "chapter": {
      "id": "chapter1",
      "sequence": 2
    }
  }
]

Now my requirement is to sort the data based on type 1st where the order should be course, chapter, and lesson, and then order based on the sequence. So my final outcome expectation is as per the above data

course1, course2, course1_chapter1, course1_chapter2, course2_chapter1, course1_chapter1_lesson1, course1_chapter1_lesson2, course1_chapter1_lesson2, course1_chapter2_lesson1

The sample data which I have mentioned is already in sorted manner but in real time scenario, I get unsorted data.

right now I have sorted just by Type using the score.
I could do the sorting by splitting the data into different variable and finally get the sorted data into single variable but would like to know if there is any advance option which I might not be aware.

A simple react project unable to compile

I am learning about react hooks and useReducer hook is giving error, in console the error comes down like this:

“Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

1. You might have mismatching versions of React and the renderer (such as React DOM)

2. You might be breaking the Rules of Hooks

3. You might have more than one copy of React in the same app

This is my App.js code:

import "./styles.css";
import React, { useReducer } from "react";
import DigitButton from "./DigitButton";


 export const ACTIONS = {
    ADD_DIGIT : 'add-digit',
    CHOOSE_OPERATION: 'choose-operation',
    CLEAR: 'clear',
    DELETE_DIGIT: 'delete-digit',
    EVALUATE: 'evaluate'
}


function reducer(state, {type, payload }) {
    switch(type){
        case ACTIONS.ADD_DIGIT:
            return{
                 ...state,
                CurrentOperand : `${state.CurrentOperand || ""}${payload.digit}` ,   
            }    
    }
}

    


function App(){

const [{CurrentOperand, PreviousOperand, Operator}, dispatch] = useReducer(reducer, {})


    return(
        <div className="calculator-grid">
            <div className="output">
                <div className="previous-output">{PreviousOperand} {Operator}</div>
                <div className="current-output">{CurrentOperand}</div>
            </div>

            <button className="span-two">AC</button>
            <button> DEL</button>
            <button> ÷</button>
            <DigitButton digit = "1" dispatch = {dispatch}></DigitButton>
            <button> 2</button>
            <button> 3</button>
            <button> *</button>
            <button> 4</button>
            <button> 5</button>
            <button> 6</button>
            <button> +</button>
            <button> 7</button>
            <button> 8</button>
            <button> 9</button>
            <button> -</button>
            <button> .</button>
            <button> 0</button>
            <button className="span-two"> =</button>
        </div>
    )
}

export default App();

This is the DigitButton.js code:

mport { ACTIONS } from "./App"

export default function DigitButton({ dispatch, digit }) {
  return (
    <button
      onClick={() => dispatch({ type: ACTIONS.ADD_DIGIT, payload: { digit } })}
    >
      {digit}
    </button>
  )
}

I tried to check if different react versions are conflicting each other and i did not find that to be the case. Also made a completely different project directory , still getting the same issue..

Google Map doesn’t display on native Mac monitor, but same window moved to external monitor works fine on page reload

I’m using the Google Maps JS API to load and configure a map. In our testing, we noticed that when the map page (https://silomillstx.webdevdla.cc/location/) is loaded on a Mac with Mac display (built-in display, or laptop display), in MOST cases the map only displays a solid grey, and when the mouse is used to try and move the map, it throws “InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value” errors.

Map showing grey on native monitor

Now, here’s the truly bizarre part. If I move the exact same window from my laptop screen to one of my external displays (2 over HDMI, 1 over USB-C) and reload the exact same page, it displays and behaves correctly.

Map showing correctly on external monitor

If I move the window back to the native display, the page appears correctly until I reload the page, at which point I’m back to a solid grey, non-working map. ABSOLUTELY no difference in the page code. Literally, the only difference is the display on which the window loading the code is showing.

  • The most consistent behavior is seen when the window is maximized to act as virtual desktop.
  • When not acting as a virtual desktop, the behavior is a bit less consistent – if initially loaded on one display and then moved to another, it will keep non-working behavior until loaded at fullscreen, but if loaded on an external display (where it works) and then moved to the native display and reloaded, it stops working correctly.
  • consistent behavior is seen on three other Macs, with a mix of Intel and M2 processors.
  • consistent behavior is seen across Safari 16.5, Chrome 115, Vivaldi 6.1, MS Edge 115, and Firefox 116.
  • The behavior is ALSO seen on browserStack.com test systems when the browserstack window is displayed on the native vs external monitor.
  • All-in-one Macs have occasionally seen the map load correctly, but mostly not.
  • It also doesn’t appear to load on iPads.

So, previous versions of my map generating code worked everywhere, and basically used PHP to retrieve the map settings and then echo out the JS code. It was messy but it worked.

This version runs PHP to pull all the settings into an array that is then turned into JSON and attached to the document object. Then, JS code is used to retrieve the values and run the JS API code. Much cleaner, except for this one issue.

I’ve used Math and Number classes to make sure the lat/lng are rounded to 6 decimal places and passed as numbers, not strings. (Same with zoom level, but rounded to an integer.)

At this point, I’m at a bit of a loss. All I can imagine is that somehow the PHP array->JSON has munged something up, but why it would only affect native Mac displays and not external displays on the same computer, same browser, same browser window, even, is quite beyond me.

I need a lifeline!

Needs Guideline for Developing Helpdesk/Ticketing system [closed]

Can someone guide me about creating helpdesk/ticketing system with in my comapny. I am new in development although knows basics (I want to get help which tool/technology/framework will be best for building front end and backend development) if someone guide me in detail , I will be very thankful to him.

I have basic job responsibility of Retail Apparel Chain Brand IT Managerial Duty (Network & Servers) having 40 stores nationwide icluding 2 Main warehouses and Head Office teams as well but as per Management decisions I needs to develop ticketing system as own (not want to use freeware). I need help someone guide me which tools and languages i should use for developing A to Z (Front end, Backend, DB tool) this helpdesk.

Tahnk You.

Want to start by learning step by step

Explode doesn’t work with a string coming from JS

// js
<script>
    // when button clicked
    let tags = 'foo,bar';
    elem.innerHTML += `<x-post tags="${tags}"></x-post>`
</script>
// post.blade.php
@php
    var_dump($tags); // string(9) "foo,bar"
    $tags = explode(',',$tags); // exploding
    echo "<br>";
    var_dump($tags); // array(1) { [0] => string(9) "foo,bar"} 
@endphp

How can i fix it? And why this is working correctly when i writing tags=”foo,bar” ?

Expecting: array with foo and bar.

Tryed: JSON.stringify(), array, array with JSON.stringify().

Actually, I’m sending a post with tags via ajax so that they load after clicking on the button, like pagination. It works without tags, but such a problem has arisen with them.

Maybe you know how i can normally send an array to a blade component like in php?

example

Is it possible to change multiple values with the help of a single input slider?

Is it possible to change multiple values with a single input slider? Because I tried many times but was unable to change different values. I want to change the value of 50,000 which is at the top of the slider, and the value of 250k which is in the unique view’s container. When we move the slider forward the 50,000 value should be changed to 10,000 per step i.e. 50,000 then 60,000 then 70,000 and so on till 1,000,000. And the value of 250k should be changed to 50K per step i.e. 250k then 300k then 350k and so on till 5M. I have made this in HTML, CSS, and JavaScript. Codes are as follows-

const input = document.querySelector("input"),
        number = document.querySelector(".slide-value"),
        uniqueViews = document.querySelector(".unique_views");

    input.addEventListener("input", () => {
        number.textContent = input.value.replace(/B(?=(d{3})+(?!d))/g, ",");
    });
.campaign {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .campaign .campaign-details {
        display: flex;
        align-items: center;
        flex-direction: column;
        width: 75%;
        background: gray;
        box-shadow: 5px 5px 4px rgba(0, 0, 0, .16);
        border-radius: 10px;
        margin-top: 60px;
        padding: 20px 0;
    }

    .campaign .campaign-details .campaign-container .campaign-cards {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 32px;
        margin: 0 10%;
    }

    .campaign .campaign-details .campaign-container .campaign-cards .card {
        width: calc(25% - 30px);
        border: 1px solid red;
        height: 50px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;
        padding: 35px 30px;
    }

    .campaign .campaign-details .campaign-container .campaign-slider {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .campaign .campaign-details .campaign-container .campaign-slider .wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 130px;
        width: 100%;
        border: 1px solid red;
    }

    .campaign .campaign-details .campaign-container .campaign-slider .wrapper .slide-value {
        font-size: 27px;
        font-weight: 500;
        color: #333;
        width: 70px;
        text-align: center;
    }

    .campaign .campaign-details .campaign-container .campaign-slider .wrapper input {
        width: 100%;
        appearance: none;
        height: 12px;
        background-color: #bdd6f9;
    }

    .campaign .campaign-details .campaign-container .campaign-slider .wrapper input::-webkit-slider-thumb {
        appearance: none;
        height: 18px;
        width: 18px;
        border: 2px solid #fff;
        background-color: #fff;
        box-shadow: 0.5px 0.5px 4px -1.5px #000;
    }

    .campaign .campaign-details .campaign-container .campaign-slider .wrapper .min-max-value {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .campaign .campaign-details .campaign-container .campaign-matrics {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 20px;
    }

    .campaign .campaign-details .campaign-container .campaign-matrics .matrics-block {
        border: 1px solid red;
        background-color: #fff;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 10px 60px;
        width: 50%;
        margin: 0 20px;
    }
<div class="campaign">
        <h2 class="header custom-cursor">Making Influencer Campaign Simple</h2>
        <div class="details campaign-details">
            <div class="campaign-container">
                <div class="campaign-cards">
                    <div class="card">
                        <div class="title">
                            <h3>Traffic</h3>
                        </div>
                    </div>
                </div>

                <div class="campaign-slider">
                    <div class="wrapper">
                        <span class="slide-value">50,000</span>
                        <input type="range" min="50000" step="10000" max="1000000" value="50000" />
                        <div class="min-max-value">
                            <p>Min: ₹50,000</p>
                            <p>Max: ₹1,000,000</p>
                        </div>
                    </div>
                </div>

                <div class="campaign-matrics">
                    <div class="matrics-block">
                        <div class="matrics-title">
                            <h4>Unique Views</h4>
                        </div>
                        <div class="matrics-value">
                            <h2 class="unique_views">250K</h2>
                        </div>
                    </div>

                    <div class="matrics-block">
                        <div class="matrics-title">
                            <h4>Cost per View</h4>
                        </div>
                        <div class="matrics-value">
                            <h2>0.2</h2>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Reactjs Website is showing 404 page on google cache

Think like a reactjs developer with good seo, I created the website in reactjs and I added the website url to the google console to get ranked. Everything is working fine on the code side but google is storing cache of the webiste which is not good.

https://webcache.googleusercontent.com/search?q=cache:http://websouls.com/shared-hosting

that’s the url I recived from the google if I hit this url “cache://mysite.com/shared-hosting” , so this show 404 component.

okay so this is wrong if the route is “http://websouls.com/shared-hosting” so it’s means it will go to the shared hosting component.

404 component means this line of code

so I debug the issue, I put the console.log in the App.js file and I add these line

const location = useLocation();

const currentURL = location.pathname;

console.log(“current route is: “, currentURL)
console.log(“full url: “, window.location.href)

so the google url is showing me the “current route is: /search” but this /search is not in the routes. If I’m checking the route is “/shared-hosting” it’s means the route must be ‘/shared-hosting”

I’m looking for the perfect solotion that rank mysite pages on google.

For example if we hit this url ” http://webcache.googleusercontent.com/search?q=cache%3A%2F%2Freact.dev%2F&rlz=1C1GCEA_enPK1020PK1020&oq=cache%3A%2F%2Freact.dev%2F&gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIGCAEQRRg60gEINTkyMGowajeoAgCwAgA&sourceid=chrome&ie=UTF-8&safe=active&ssui=on” this is the cache version of the “react.dev” website which is perfectly cached by the google. I want to do that same stuff in mysite.

Cant get the full path of the file Django boto3 AWS S3 Ajax Upload in chunks

I cant get the full path of the client side to upload to AWS S3

Ajax:

upload_file(start, path) {
    var end;
    var self = this;
    var existingPath = path;
    var formData = new FormData();
    var nextChunk = start + this.max_length + 1;
    var currentChunk = this.file.slice(start, nextChunk);
    var uploadedChunk = start + currentChunk.size
    if (uploadedChunk >= this.file.size) {
        end = 1;
    } else {
        end = 0;
    }
    formData.append('file', currentChunk);
    formData.append('filename', this.file.name);
    formData.append('end', end);
    formData.append('existingPath', existingPath);
    formData.append('nextSlice', nextChunk);
    $('.filename').text(this.file.name)
    $('.textbox').text("Uploading file")
    $.ajaxSetup({
    // make sure to send the header
        headers: {
            "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,
        }
    });
    $.ajax({
        xhr: function () {
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    if (self.file.size < self.max_length) {
                        var percent = Math.round((e.loaded / e.total) * 100);
                    } else {
                        var percent = Math.round((uploadedChunk / self.file.size) * 100);
                    }
                    $('.progress-bar').css('width', percent + '%')
                    $('.progress-bar').text(percent + '%')
                }
            });
            return xhr;
        },

        url: '/fileUploader/',
        type: 'POST',
        dataType: 'json',
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        error: function (xhr) {
            alert(xhr.statusText);
        },
        success: function (res) {
            if (nextChunk < self.file.size) {
                // upload file in chunks
                existingPath = res.existingPath
                self.upload_file(nextChunk, existingPath);
            } else {
                // upload complete
                $('.textbox').text(res.data);
                alert(res.data)
            }
        }
    })

and my views.py

def create_post(request):
# s3_client=boto3.client('s3')
s3 = boto3.client('s3', region_name=settings.AWS_S3_REGION_NAME, aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
                      aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
categories_1 = Category.objects.all()
if request.method == 'POST':   
    file = request.FILES['file'].read()
    file_name_s3 = request.POST['filename']
    fileName= request.POST['filename'].replace(' ', '')
    fileName_STR = re.sub("[^A-Z]", "", fileName,0,re.IGNORECASE) + '.mp4'
    existingPath = request.POST['existingPath']
    end = request.POST['end']
    image = request.FILES.get('image', False)
    imageName = request.FILES.get('imagename', False)

    if image != False:
            image = request.FILES['image'].read()
            imageName= request.POST['imagename'].replace(' ', '')
    else:
            pass
    title = request.POST['title']
    tags = request.POST['tags']
    categories = parse_ids(request.POST['categories'])
    description = request.POST['description']
    nextSlice = request.POST['nextSlice']


    if file=="" or fileName_STR=="" or existingPath=="" or end=="" or nextSlice=="":
        res = JsonResponse({'data':'Invalid Request'})
        return res
    else:
        if existingPath == 'null':
            path = 'media/uploads/video_files/' + fileName
            
            if image != False: 
                with open(path, 'wb+') as destination: 
                    destination.write(file)
                imagePath = 'media/thumbnail/' + imageName
            else:
                pass
            if image:
                with open(imagePath, 'wb+') as destination:
                    destination.write(image)
            else: 
                pass
            
            path = 'media/uploads/video_files/' + fileName_STR
# THIS IS THE PROBLEM...................
                s3.upload_file(file_name_s3 ,bucket,str(fileName_STR))
# ............................................
            FileFolder = Post()
            FileFolder.video = 'uploads/video_files/'+fileName_STR
            FileFolder.existingPath = fileName_STR
            FileFolder.eof = end
            FileFolder.title = title
            FileFolder.author = request.user
            FileFolder.description = description

            if image == False:
                FileFolder.thumbnail = None
            else:
                FileFolder.thumbnail = 'thumbnail/' + imageName

            FileFolder.approved = True
            FileFolder.save()
            tag_list = taggit.utils._parse_tags(tags)
            FileFolder.tags.add(*tag_list)
            categories_post = Category.objects.filter(id__in=categories)
            if categories_post:
                for category in categories_post:
                    FileFolder.categories.add(category)
            if int(end):
                res = JsonResponse({'data':'Uploaded Successfully','existingPath': fileName})
            else:
                res = JsonResponse({'existingPath': fileName_STR})
            return res
        else:
            path = 'media/uploads/video_files/' + existingPath
            model_id = Post.objects.get(existingPath=existingPath)
            if model_id.title == title:
                if not model_id.eof:
                    with open(path, 'ab+') as destination: 
                        destination.write(file)
                    if int(end):
                        model_id.eof = int(end)
                        model_id.save()
                        res = JsonResponse({'data':'Uploaded Successfully','existingPath':model_id.existingPath})
                    else:
                        res = JsonResponse({'existingPath':model_id.existingPath})    
                    return res
                else:
                    res = JsonResponse({'data':'EOF found. Invalid request'})
                    return res
            else:
                res = JsonResponse({'data':'No such file exists in the existingPath'})
                return res
return render(request, 'main/create_post.html', {'categories': categories_1})

HOW TO GET THE PATH OF THE FILE SO I CAN UPLOAD TO AWS S3, no matter what i tried it doesnt gives me the full path

FileNotFoundError: [Errno 2] No such file or directory: ‘Bones – TheArtOfCremation-tqSpI1Jm0YE-1080p.mp4’

let declarations being hoisted to top of their scope

If I write this then it prints undefined:

let a  
console.log(a)
a = 20

but why does this return an error, then?

console.log(a)
let a = 20

a gets hoisted to the top in case 2 and since JavaScript doesn’t assign any value to let in memory allocation phase it returns error. But isn’t the condition similar in case 1 also? Then why does it print undefined in case 1?

Cannot read properties of undefined on button click after deleting selected rows

Cannot read properties of undefined on button click after deleting selected rows .After deleting or adding rows , when i click on row button it is showing undefined , after refreshing the page it is working correctly after refreshing the page im able to get row data but i need without refreshing the page.

db.collection("Users").where("tokens", "array-contains", token).get().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
        console.log(doc.data().uid);
        console.log(key);
       if(doc.data().uid == key)
       {
            $(document).ready(function() {
            let ics=[];
            db.collection("icdetails").where("ownerid", "==", key).onSnapshot(function (querySnapshot) {
            querySnapshot.forEach(function (doc) {
                
                ics.push(doc.data());
                console.log(ics)
            })
                        var table =  $('#groupAlphaList').DataTable({
                destroy: true,
                responsive: true,
                dom: 'Bfrtip',
                    buttons: [
                      
                        'copy', 'csv', 'excel', 'pdf',
                        {
                            text: 'Delete',
                            action: function ( e, dt, node, config ) {
                              var count = $('#groupAlphaList').DataTable().rows( '.selected' ).count();

                              var checked_rows = $('#groupAlphaList').DataTable().rows( '.selected' ).data();
                              
                              for(var i=0; i<checked_rows.length; i++)
                              {
                                console.log( checked_rows[i].email);
                                var jobskill_query = db.collection('icdetails').where('email','==',checked_rows[i].email);
                                  jobskill_query.get().then(function(querySnapshot) {
                                  querySnapshot.forEach(function(doc) {
                                      doc.ref.delete();
                                  });
                                  });       
                              }
                              //  DeleteData()
                            }
                        },
                    ],
                data: ics,
                
                columnDefs: [ {
                    orderable: false,
                    className: 'select-checkbox',
                    targets:   0
                } ],
                select: {
                    style:    'multi',
                    selector: 'td:first-child'
                },
                order: [[1, 'asc']],
                columns : [
                         { "data": null, defaultContent: '' },
                        { "data" : "name" },
                        { "data" : "phone" },
                        { "data" : "iscore" },
                        { "data" : "email" },
                        { "data" : "designation" },
                        {
                            "data": null,
                            "bSortable": false,
                           "mRender": function (o) {
                            
                            return '<button class="viewbutton">View <i class="fa fa-edit"></i></button>'; }
                        },
                        
                        { "data" : "date" }
                        ],
                        }) 
                       $('#groupAlphaList tbody').on('click', '.viewbutton', function () 
{
                                var current_row = $(this).parents('tr');
                                if (current_row.hasClass('child')) {
                                    current_row = current_row.prev();
                                }
                                var data = table.row(current_row).data();
                                console.log('Row data:'+data.name);
                            });
                        
                ics=[];   
               
                  
            });
            

            });
       }
    });
  });

After deleting or adding rows , when i click on row button it is showing undefined , after refreshing the page it is working correctly after refreshing the page im able to get row data but i need without refreshing the page