I have the following function in my react js as follows which is fairly simple and returns different values based on conditions.
const checkStatus =(device:any)=> {
if(device?.patient){
return "disconnect"
} else if(!device.patient && device?.status === "DEACTIVATED") {
return "delete"
}
else {
return "enable"
}
}
above code throws and error "Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." . can anyone help me understand what is wrong here
CodePudding user response:
You are using the ternary operator in a weird way which could cause the js to not function as intended. Try removing it(note that your code may run differently than intended).
const checkStatus = (device:any) => {
if (device.patient) {
return "disconnect";
} else if (!device.patient && device.status === "DEACTIVATED") {
return "delete";
} else {
return "enable";
}
}
CodePudding user response:
It is not very clear from the question where this function is called. But some problems can be spotted which should lead to errors. Seems what is happening is that function is called in a react component, and its throwing an exception which causes the react component not to reach the return statement of its render thus throwing the exception: "Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."
3 problems can be seen in this function:
1- you are not checking if the argument device
if null. If it is null device.patient
will throw an exception.
2- you are using ternary operator in a weird way. If its to satisfy ts linting, its wrong. This can be avoided by adding a guard clause at the start of the function: if (!device) return null;
. ts will analyze the control flow and it won't require you to add the ternary operator.
3- if any
is used with typescript there is something wrong with the function. Why it should expect any
argument ? Why not an object that have patient
and status
as members ?