Append new files

I have an api running that fetches all the file names in the directory and returns me an array inside an array. Currently, I am running it every second to check if a new file is added and if so... embed it to my div. The issue is that I have to empty my html every time and then re-embed the html. Is there a better way to do this? That way I only embed new filenames rather than all again.

setInterval(function(){
    $.ajax({
        url : 'getFiles',
        success: function (data) {
            $("#pics").html("");
            console.log(data);
            $.each(data, function (k, o) {
                $.each(o, function (key, obj) {
                    $("#pics").append("<a href='#'>" + obj + "</a>");
                });
            });
        }
    });
}, 1000);

2 answers

  • answered 2018-02-13 02:03 melson.jao

    In your case, I will suggest to keep current implementation: clean all and generate the list by new received data. The reason is:

    • From performance view, clean all and regenerate it will faster than for each compare and check if duplicated => keep, remove old item or insert new item
    • the order of item can be easily kept as the received data. Won't be confused with the old item list.

    The rule I suggest is: if the new list is totally the same, return without change directly. If the list has been changed, clean all and rebuild the list directly.

  • answered 2018-02-13 02:15 Pavlo

    const images = [];
    
    setInterval(function(){
        $.ajax({
            url : 'getFiles',
            success: function (data) {
                const fetchedImages = data.images;
                if(images.length !== fetchedImages.length){ //They do not have the same elements
                  images = fetchedImages;
                  $("#pics").html("");
                  const domImages = fetchedImages.map(image => "<a href='#'>" + image + "</a>");
                  $("#pics").append(domImages.join(''));
                }
            }
        });
    }, 1000);
    

    From our discussion i was able to create this solution.

    Since you know that you only need a list of images, then you can just get it directly.

    Then you can check if the images which are saved locally have the same amount of elements which you got from the server.

    If they do not match, then it must mean that the list has been changed (a side-effect could be that someone changed the name of a file, then the length would be the same)

    Now we just empty the #pics HTML, create a new array where each element is wrapped in an <a> tag

    Lastly join just takes an array and converts it to a string. '' means that there shouldn't be any text between each element, so the string looks like this

    "<a href='#'>image1.jpg</a><a href='#'>image2.jpg</a><a href='#'>image3.jpg</a>"