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?
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.
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
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
Related
Ok, newbie alert, but I have a react component like below. I want to load user object and then show user.name and possible other nested properties, like user.address.street.
const ProfileDisplay =()=>
{
const [user, setUser] = useState(null);
useEffect(()=>{
async function populate(){
const user = await fetch('server/getUserProfile/'...);
setUser(user)
}
populate();
},[whatevs])
return (<FancyLookingForm>...<span>Your name is {user.name}</span>...</FancyLookingForm>);
}
...
During the time the user-object is loaded I want the form to be displayed, but empty. The alternatives I see is either create a dummy object that looks like the one that will come from the server and use that as init object to useState(). The other alternative is to use an if null-check on every place I use the user-object.
I will do quite alot of forms, so I want to check if there is a better way to do this?
I have written a utility function that will help you.
/**
* object is the forms data container in your example user
* property is field name e.g. name, age
*/
function getPropertryValue(object, property) {
if(!object) return "";
const keys = Object.keys(object);
const keysLength = keys.length;
for(let i= 0; i < keysLength; i++) {
const key = keys[i];
if(key == property) {
return object[key];
}
if(typeof object[key] === 'object'){
return utilFindHas(object[key], property);
}
}
return "";
};
So instead of using {user.name} use getPropertyValue(user, "name")
It will return empty string if it doesn't exist yet.
I'm creating plugin for wordpress on react js and got an issue.
When user is entering in admin page and choose for example posts,
I'm checking if it is not a post, so user can't use customizable block:
if ( type !== "post" ) {
return <p>{__("Sorry, Post Navigation block is available only for Posts")}</p>;
}
and it's working, but in wordpress can be more types of posts, so I'm trying to use || inside this condition to check on another type:
if ( type !== "post" || type !== "portfolio" ) {
return <p>{__("Sorry, Post Navigation block is available only for Posts and Portfolio")}</p>;
}
And now is my problem, it's not working.
Variable type I'm getting from here:
const type = wp.data.select('core/editor').getCurrentPostType();
it returns a string.
What am I doing wrong?
Can you help me, please?
if ( type !== "post" || type !== "portfolio" ) {
This will always be true. If type is "post", then it will not be equal to "portfolio". If it's "portfolio", then it will not be equal to "post". And if it's anything else, it will not be equal to either.
Change it to use &&
if ( type !== "post" && type !== "portfolio" ) {
I have a conditional statement where I'm checking if the path includes hello and buy in them then return null. (Path is getting passed to the component as props). But if path isn't getting passed I don't want the page to break. How do I write a conditional here to check if the path is available? This is what I wrote
if path ? ((path.includes('/hello') || (path.includes('/bye')) : '') {
return null
}
Instead of checking if the path prop is undefined, you can give it a default value of an empty string and keep your code as it is.
function MyComponent({ path = '' }) {
if (path.includes('/hello') || path.includes('/bye')) {
return null;
}
// ...
}
I'm trying to render a message to a span tag specific to an item in a list. I've read a lot about React 'refs', but can't figure out how to populate the span with the message after it's been referenced.
So there's a list of items and each item row has their own button which triggers an API with the id associated with that item. Depending on the API response, i want to update the span tag with the response message, but only for that item
When the list is created the items are looped thru and each item includes this
<span ref={'msg' + data.id}></span><Button onClick={() => this.handleResend(data.id)}>Resend Email</Button>
After the API call, I want to reference the specific span and render the correct message inside of it. But I can't figure out how to render to the span at this point of the code. I know this doesn't work, but it's essentially what I am trying to do. Any ideas?
if (response.status === 200) {
this.refs['msg' + id] = "Email sent";
I recommand using state. because string refs legacy (https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)
const msgs = [
{ id:1, send:false },
{ id:2, send:false },
{ id:3, send:false },
];
this.state = {
msgs
};
return this.state.msgs.map((msg, index) => {
const status = msg.send ? "Email Sent" : "";
<span>{ status }</span><Button onClick={() => this.handleResend(index)}>Resend Email</Button>
});
async handleResend (index) {
const response = await callAPI(...);
if(reponse.status !== 200) return;
const newMsgs = _.cloneDeep(this.state.msgs);
newMsgs[index].send = true;
this.setState({
msgs: newMsgs
})
}
The workaround is set innerText
this.refs['msg' + id].innerText = "Email sent";
But rather than using ref try to use state to update elements inside render.
i was facing with this issue right now and i figured it out this way:
// currentQuestion is a dynamic Object that comes from somewhere and type is a value
const _target = `${currentQuestion.type}_01`
const _val = this[`${_target}`].current.clientHeight // here is the magic
please note that we don't use . after this to call the ref and not using refs to achieve what we want.
i just guessed that this should be an Object that would hold inner variables of the current object. then since ref is inside of that object then we should be able to call it using dynamic values like above...
i can say that it worked automagically!
I would like to filter a Firebase path and see if a child exist in my path.
I just want to return the values wich have a path call "reponses". It works but when the path doesn't have this Child, it throw me this error :
firebase.js:283 Uncaught TypeError: Cannot read property '$value' of
firebase.js:276 FIREBASE WARNING: Exception was thrown by user callback.
TypeError: Cannot read property '$value' of undefined
I use Firebase-util and Angularfire like that :
var ref = firebase.database().ref();
var nc = new firebase.util.NormalizedCollection(
ref.child('accounts/' + $localStorage.accountId + '/demandes'),
[ref.child('demandes'), 'widget2']).select('widget2.duree', 'widget2.derniere_modification', 'widget2.reponses', 'widget2.exp', 'widget2.ajout_le', 'widget2.localisation').
filter(function(data, key, priority) {
return data.reponses.$value !== null; // This cause problems !
}).ref();
$scope.items = $firebaseArray(nc);
How can I do to test in a proper way other than return data.reponses.$value !== null; ? Thank you
It sounds like data.responses is undefined so you could check for $value like this:
.filter(function (data, key, priority) {
return data.responses && data.responses.$value !== null;
}).ref();
This makes sure that there is a responses field on data before you probe it for $value.