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:
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?!
CodePudding user response:
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!
CodePudding user response:
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";
}
}

