0

This code worked previously, but now that I upgraded my expo version I am getting the error

TypeError: Cannot assign to read only property 'userId' of object '#'

export interface CurrentUser {
  userId: string;
  ...
}

This is the creation of the object

import { CurrentUser } from "../types/CurrentUser";

let currentUser: CurrentUser|null = null;

This is the assignment that is throwing the error.

export const setUserToken = async (tokenData: TokenResponse) => {
  if (tokenData) {
    currentUser = {
      userId: "",
      ...
    };
  }
  try {
    await currentUserStore.setState(currentUser);
    const result = await setClientsInfoByUsername();
}

export const setClientsInfoByUsername = async () => {
const data = await httpPost(...);

if (currentUser) {
currentUser.userId = data?.employee_id || ""; //Throws error
}

I'm not super familiar with React Native, so any help would be much appreciated.

I'm using expo version 54.0.21

7
  • I left out the line before my property assignment, I have a null check in place. Commented Nov 3 at 20:43
  • Where does that object come from? Is it frozen? Commented Nov 3 at 21:01
  • It is created as an interface and imported in. I will add that code to the question Commented Nov 3 at 21:20
  • thats at typescript/compile time. this error is a runtime error. thats what we need to know Commented Nov 3 at 21:33
  • When and where is currentUser being assigned. We see that you import the type. But you haven't shown the value. It's the value that is for some reason read-only. It's unclear why but it strongly implies you're not supposed to change it. Commented Nov 4 at 5:51

1 Answer 1

-1

The error means you're trying to change a value on an object that’s either null or read-only.In your code, currentUser starts as null, so this line fails:

currentUser.userId = data?.employee_id || "";

You can fix it by giving currentUser an initial value:


let currentUser: CurrentUser = { userId: "" };
currentUser.userId = data?.employee_id || "";

Or, if it can be null:

if (currentUser) {
  currentUser.userId = data?.employee_id || "";
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is not the error you get when trying to assign a property to null. The error only shows up when it's an object but the property that you're trying to assign is not writeable. jsbin.com/bilezupafa/1/edit?js,console

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.