Search code examples
javascriptreactjsstateflux

React not overwriting state


I'm usign setState to change the state of my component.

It works fine until i need to delete an element from the state.

Let's pretend i have this on my store:

{
    0: {name: foo},
    1: {name: bar}
}

If I add another element, it works just fine:

store[2] = {name: hohoho};
setState(store, console.log(this.state));

With the code above, I end up with the expected state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But if I delete one of the elements from the store and change the state again, it doesn't delete from the state:

delete store[2]

If I console.log(store), I get:

{
    0: {name: foo},
    1: {name: bar}
}

then:

setState(store, console.log(this.state))

gives me:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
}

But stranger than this, is if I add another element to the store, and set the state after:

store[3] = {name: heyheyhey};
setState(store, console.log(this.state));

I end up with the following state:

{
    0: {name: foo},
    1: {name: bar},
    2: {name: hohoho},
    3: {name: heyheyhey}
}

Even if console.log(store) gives me the following:

{
    0: {name: foo},
    1: {name: bar},
    3: {name: heyheyhey}
}

Can someone please help me understand whats going on?

EDIT

Since some comments said delete might be the problem, i changed the way I'm deleting from my store:

var temp = {};
for (var x in store) {
    if (x != id) {
        temp[x] = store[x];
    }
}
store= temp;

But I'm still experiencing the same problem.


Solution

  • To answer the question like I mentioned in my comment. Delete doesn't free up memory like the key word makes you think it does.

    According to MDN Delete

    Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references

    So all you have to do is replace it with a new object instead of modifying the old one.

    Edit:

    Try something like this

    cloneObject(obj) {
            if (null == obj || "object" != typeof obj) return obj;
            var copy = obj.constructor();
            for (var attr in obj) {
                if (obj.hasOwnProperty(attr)) {
                    copy[attr] = obj[attr];
                }
            }
            return copy;
    }