0

The console is showing a new Object but I still get the error

const GetNo = (): string => {
        console.log(record);
        if (record.no !== "")
            return record.no;   //<-- Cannot read properties of undefined
        else
            return todos[todos.length - 1].no + 1;
    }

console:

enter image description here

EDIT: record is type of object (see picture above) and im creating it via Button onClick where i modify a state this.setState({ selectedRecord: new ToDoClass() . After that I redner the FC with the form.

EDIT 2: I tried the new Syntax:

const GetNo = (): string => {
        if (record == null) {
            console.log("1");
            return "2";
        }
        else if (record.no != null) {
            console.log("2");
            return record.no;
        }
        else {
            console.log("3");
            return todos[todos.length - 1].no + 1;
        }
    }

and when the record is: new ToDoClass() it return in the console a 2 but it should go inside the first statement?!

3
  • What's the type of record and where is it initialized? Commented Jan 15, 2022 at 21:51
  • @tokland I edit the post Commented Jan 16, 2022 at 11:48
  • where is record defined in your code, e.g. const record = ....? Commented Jan 16, 2022 at 12:43

2 Answers 2

3

Your object record is defined outside of the function and may not be initialized at the execution time of the function.

I recommend you to:

  • Pass the object as a parameter of the function
  • Check that record is defined

By the way if you're using Typescript and there is a possibility that the record is not defined when passed to the function, you should get a warning at the line where you call GetNo(record).

const GetNo = (record: Record): string => {
   if (record) {
     // ...
   }
}

I hope it will be helpful!

Sign up to request clarification or add additional context in comments.

1 Comment

The check that the record is defined works but now it always return this if statement and dont go into the other statements
0

I don't know why it behaves like this but I solved it with a Try-Catch statement.

const GetNo = (): string => {
   try {
      if (record.no !== "")
         return record.no;
      else
         return todos[todos.length - 1].no + 1;
   }
   catch {
      return "0";
   }
}

Comments

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.