I have two routes, /Profile
which shows the user their own profile.
(it doesnt need to request this because their profile is already stored in state)
Then the second /Profile/....
which shows the user other profiles.
(it does need to request this because the state does not store all other users)
To have this functionality I have tried inputting this undefined / null check but it doesn't fail when the params are empty:
const getRequest = async () => {
const user_response = null;
console.log("param",params)
console.log("param id",params.id)
if (params !== null || params !== undefined) {
console.log("params true")
if (params.id !== null || params.id !== undefined) {
console.log("id true")
}
else{
console.log("false")
}
}
else{
console.log("false")
}
The following is the console outputs when no params are passed:
> param {}
> param id undefined
> params true
> id true
The following is the console outputs when params are passed:
> param {id: '321'}
> param id 321
> params true
> id true
How can I make it work as intended?
CodePudding user response:
If your user ID can't be falsy (e.g. 0
is not a valid user ID, or ''
isn't), then just
const userId = params?.id || null;
without any other fuss – userId
it'll be either the ID if it's truthy, or null
.
CodePudding user response:
the empty object still return true, so if you want to check the object is empty or not you must do something like this:
const obj = {};
const isEmpty = Object.keys(obj).length === 0;
then you can check the param object with this
CodePudding user response:
It looks like when you're not passing any params, "params" is default an empty object which is bypassing your if statementes ( because it is actually different than null and undefined) You need a more clear condition; can use lodash library which has a method _.isEmpty() to check for empty objects or as other have stated use the Object.Keys length