Tips on how to refresh the identifiers within an array stored in local storage

I have a collection of list items with unique IDs that correspond to IDs stored in an array in local storage. When I delete a list item, the corresponding element is also removed from the array. However, after refreshing my browser, the IDs of the list items update but the IDs in local storage do not. How can I update the IDs in local storage to match the list item IDs?

    const listaTweets = document.getElementById('lista-tweets');
let li;
let comment;

evenListeners();


function evenListeners() {
    document.querySelector('#formulario').addEventListener('submit', addTweet);
    listaTweets.addEventListener('click', deleteComment);
    document.addEventListener('DOMContentLoaded', localStorageDone)
}

function addTweet(e) {
    e.preventDefault();
    comment = document.getElementById('tweet').value;
    if(comment) {
        createLi(comment)
        const liId = li.id
        addCommentLocalStorage(comment, liId)
    }
}

function createLi(comment) {
    const deleteButton = document.createElement('a');
    deleteButton.classList = 'delete-comment';
    deleteButton.innerText = 'x';

    li = document.createElement('li');
    li.innerText = comment;
    li.appendChild(deleteButton);

    listaTweets.appendChild(li);

    if (li) {
        for (let i = 0; i < listaTweets.children.length; i++) {
            li.setAttribute('id', 'tweet__number' + i)
        }
    }
}

function deleteComment(e) {
    e.preventDefault();
    li = e.target.parentElement;
    if(e.target.className === 'delete-comment') {
        li.remove();
        deleteCommentLocalStorage()
    }
}

function addCommentLocalStorage(comment, liId) {
    let arrayComments;
    let idComment = liId
    arrayComments = getFromLocalStorage();

    arrayComments.length === 0 ? idComment = liId : (arrayComments[arrayComments.length - 1].idComment)

    let object = {
        id: idComment,
        com: comment
    }
    
    arrayComments.push(object)
    localStorage.setItem('comments', JSON.stringify(arrayComments))
}

function getFromLocalStorage() {
    let arrayComments;
    if(localStorage.getItem('comments') === null) {
        arrayComments = []
    } else {
        arrayComments = JSON.parse(localStorage.getItem('comments'))
    }
    
    return arrayComments
}

function localStorageDone() {
    let arrayComments;
    arrayComments = getFromLocalStorage();
    arrayComments.forEach(function(comment){
        createLi(comment.com)
    })
}

function deleteCommentLocalStorage() {
    let arrayComments = getFromLocalStorage();

    arrayComments.forEach(function(comment){
       if(comment.id === li.id) {
            let i = arrayComments.indexOf(comment);
            arrayComments.splice(i, 1);
        }
        
        localStorage.setItem('comments', JSON.stringify(arrayComments));
    })
}

Answer №1

There is a typo that I have discovered.

// before 
arrayComments.length === 0 ? idComment = liId : (arrayComments[arrayComments.length - 1].idComment)
// after
arrayComments.length === 0 ? idComment = liId : (arrayComments[arrayComments.length - 1].id)

Upon fixing the typo, it has come to my attention that there seems to be an issue with the matching of ids between listaTweets and arrayComments when adding or removing items. It would be advisable to look into this further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having dual fixed navigation bars on a single webpage

I am looking to create two fixed navigation bars, one at the top and another in the center of the page. The idea is that when scrolling reaches the second nav bar, the first one should hide (or become relative) and the second one should become fixed. Then, ...

What is the best way to modify navbar-default to navbar-inverse when scrolling?

On the header of my webpage, the primary navigation class is called: navbar navbar-default navbar-fixed-top bg I am attempting to create a smoother scroll animation by changing the class when scrolling as follows: navbar navbar-inverse navbar-fixed-top ...

How can I fill in 3 textboxes with the selected Autocomplete value in MVC 4?

I am trying to implement autocomplete functionality in my form, where a text box is already attached to autocomplete. However, I am unsure how to trigger the ActionResult (which returns JSON) when a value is selected, extract the JSON result, and populate ...

Tips for replicating PaddingTop using Grid Material UI and populating blank rows at the beginning

Imagine we are working with a Grid component const App = () => { const useStyles = makeStyles(theme => ({ root: { flexGrow: 1 }, paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.tex ...

Rational numbers arranged in a C++ array

When working with fractions in C++, I am unsure of the correct data type to use for an array so that I can retrieve the numbers as fractions when needed. Float numbers [5]={7/6,1/6,5/66,1/42,1/30,4389/698} ; cout << numbers[3] ; The current output i ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Swapping the image source using a Vue dropdown menu

Recently I started using Vue and decided to implement a dropdown menu component (). The component pulls its list items from a JSON array structured as follows: <template> <div id="app"> <div id='container'> ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

The camera feature in Ionic Cordova seems to be malfunctioning

I am attempting to implement the ionic cordova camera feature. Here is the code snippet I have: HomePage.html <ion-view view-title="Example"> <ion-content> <img ng-show="imgURI !== undefined" ng-src="{{imgURI}}"> <img ng-s ...

Access the value of a JSON property, return null if the key is not found, all in one line of JavaScript code

How about a fun analogy in Python: fruits_dict = {"banana": 4, "apple": 3} num_apples = fruits_dict.get("apple", None) num_oranges = fruits_dict.get("orange", None) print(num_apples, num_oranges) The result would be: 3 None If we switch gears to Jav ...

Tips for preventing a function from being triggered twice during a state change

I'm currently working with a react component that looks like this: const [filter, setFilter] = useState(valueFromProps); const [value, setValue] = useState(valueFromProps); const initialRender = useRef(true); useEffect(() => { if (initialRender. ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

The function myComponent.map does not exist

I am currently storing information that I am trying to pass to a component responsible for creating Tabs and TabPanel components (Material-UI) based on the provided data. Here is how the information is structured: let eventCard = [ { title: "T ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

Node.js: Determine if an object is missing a certain property

My goal is to check if a property 'lessons' (not inherited) is not present in the object. The following conditions all evaluate to true: (typeof obj['lessons'] == undefined) (!(obj.hasOwnProperty('lessons'))) (!(hasOwnPrope ...

Set the ng-model attribute to "searchText" on an input within Angular JS, assigning it a value when a list item is clicked

Using angular.js (ng-model="searchText"), I have implemented a searchable list with an input field. When a list item is clicked, the content of the selected item can be displayed using {{selected | json}}. My goal is to set the value of the input to the se ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...