1

I working on an app where I have to receive data from back which contains userdetail object.

I want to assign a current accessToken to the userdetail object in my code:

useEffect(() => {
        if (session?.user && pageLoad) {
            try {
                axios
                    .get(`${process.env.CONTENT_GHAR_API_URL}/auth/userDetail`, {
                        headers: {Authorization: session.user.data.accessToken},
                    })
                    .then(response => {
                        setPageLoad(false);
                        console.log("response", response);
                        if (response?.data) {
                        
                            response.data?.message?.userDetail?.accessToken =session?.user?.data?.accessToken;
                            localStorage.setItem("uniqueId",response.data?.message?.userDetail?._id,);
                            dispatch(userDetail(response.data.message.userDetail));
                        }
                    });
            } catch (error) {
                setPageLoad(false);
            }
        }
    }, [session]);

When I run the app, I ended up with the error Syntax error: Invalid left-hand side in assignment expression.* for the code shown above. Why? What is the correct way to update that value then?

enter image description here

  • You are using optional chaining on the left side of an assignment, which is not possible I believe. See https://stackoverflow.com/questions/58878948/optional-chaining-on-the-left-side-in-javascript – nucleaR Oct 04 '22 at 08:37

2 Answers2

1

response.data?.message?.userDetail?.accessToken =session?.user?.data?.accessToken;

Optional chaining is not something that we can run on the LHS of an expression. If you want to create dynamic keys, you can try using the bracket notation (refer https://www.samanthaming.com/tidbits/37-dynamic-property-name-with-es6/)

Gibz
  • 89
  • 6
1

In addition to @Gibz answer, To make it works you need to check first if the userDetail already exists, then remove the Optional chaining operator from the left side.

if (response.data?.message?.userDetail) 
  response.data.message.userDetail.accessToken = session?.user?.data?.accessToken;

or

response.data?.message?.userDetail &&
  (response.data.message.userDetail.accessToken = session?.user?.data?.accessToken);
Mina
  • 14,386
  • 3
  • 13
  • 26