session icon indicating copy to clipboard operation
session copied to clipboard

How do I keep a session variable from changing?

Open rdalfonso opened this issue 7 years ago • 4 comments

Seems like no matter what I do the value of req.session keeps changing.

const copySession - req.session.myObject; const changedCopy = functionThatWantsToChangeTheCopyOnly(copySession);

For some reason even assigning the req.session to a variable, and changing THAT variable, affects the original req.session?

Any ideas why?

rdalfonso avatar Apr 16 '19 00:04 rdalfonso

Please post your express-session code, middleware and controller routes.

knoxcard avatar Apr 23 '19 02:04 knoxcard

Here's the answer, but please read below to understand why this occurs

const copySession = Object.assign({}, req.session);

I must have originally read your question too quickly at first, wouldn't have asked you to post your code as this is not an express-session problem.

[Copied and pasted from good ole Stackoverflow!] All Credit Goes To: https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change

It is clear that you have some misconceptions of what the statement var tempMyObj = myObj; does. In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj and myObj are both references to the same object.

Here is a simplified illustration that may help you visualize what is happening


// [Object1]<--------- myObj

var tempMyObj = myObj;

// [Object1]<--------- myObj
//         ^ 
//         |
//         ----------- tempMyObj

As you can see after the assignment, both references are pointing to the same object.

You need to create a copy if you need to modify one and not the other.


// [Object1]<--------- myObj

const tempMyObj = Object.assign({}, myObj);

// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj

@rdalfonso - close ticket?

knoxcard avatar May 06 '19 20:05 knoxcard

@rdalfonso - close issue?

knoxcard avatar May 09 '19 00:05 knoxcard

Yes I figured it out.

rdalfonso avatar May 09 '19 02:05 rdalfonso