I was watching a tutorial video on useEffect, and i understand how useEffect fires relative to change in dependency, but what if there's an explicit "null" or "undefined" given as a dependency?
I mean.
useEffect(()=>{
},[Null/undefined])
Anybody?
Videos
check if a state variable is null, undefined, or empty, use the logical OR (||) operator along with nullish coalescing operator (??)
const [fleetOwner, setFleetOwner] = useState({ id: '', name: '' });
if (!fleetOwner?.id) {
}
There are already a few solutions above, but here's the reason for the error: operator precedence. The && has higher priority than ||, therefore p && q || r is evaluated as (p && q) || r.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence
And yes, one solution would be to put parentheses to enforce the evaluation you want, so
p && (q || r).
What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like
componentWillReceiveProps(nextProps) {
if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
}
You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value
In order to check for undefined, you can also use the typeof operator like
typeof nextProps.blog.content != "undefined"
I was face same problem ..... And I got solution by using typeof()
if (typeof(value) !== 'undefined' && value != null) {
console.log('Not Undefined and Not Null')
} else {
console.log('Undefined or Null')
}
You must have to use typeof() to identified undefined
Since switching to TypeScript I have been using a lot of optional properties, for example:
type store = {
currentUserId?: string
}
function logout () {
store.currentUserId = undefined
}However my coworkers and I have been discussing whether null is a more appropriate type instead of undefined, like this:
type store = {
currentUserId: string | null
}
function logout () {
store.currentUserId = null
}It seems like the use of undefined in TypeScript differs slightly from in Javascript.
Do you guys/girls use undefined or null more often? And, which of the examples above do you think is better?
It looks like you're trying to access the property items of a variable x.
And if x is undefined, then calling x.items will give you the error you mentioned.
Doing a simple:
if (x) {
// CODE here
}
or
if (x && x.items) { // ensures both x and x.items are not undefined
// CODE here
}
EDIT:
You can now use Optional Chaining, which looks sweet:
if (x?.items)
- In simple function you do it simply by if statement.
if(typeof x !=='undefined' && typeof x.item !=='undefined'){
}
- in JSX you do it in this way.
render(){
return(
<div>
(typeof x !=='undefined' && typeof x.item !=='undefined')?
<div>success</div>:
<div>fail</div>
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
What is the appropriate approach in React when you don't want to render anything? I remember reading an article about a similar topic a few years ago, but I'm curious about the current state.
https://www.reddit.com/r/reactjs/comments/gtyr61/null_vs_empty_fragment/
It seems that the React documentation recommends using values like null, undefined, or false when you don't want to render anything. On the other hand, mentions of an empty Fragment are hard to find.
Fragment
Conditional Rendering
Due to null and undefined will be evaluated to false in boolean context - you can just combine your checks at one place:
{
financialPerformance && financialPerformance.isConfirmed ? (
<L.Text txtGray>Confirmed</L.Text>
) : (
<L.Text txtGray>Not Confirmed</L.Text>
)
}
You could be explicit and do the following...
// Check specifically for null or undefined
if(financialPerformance === null || financialPerformance === undefined) {
// Code...
}
// Checking for zero, could be returned ( not sure on your data )
if(financialPerformance === 0 || financialPerformance) {
// Code...
}
function Comp1() {return;}
function Comp2() {return null;}
Why does the first one throw "nothing returned from render" and second just works? Is it because of some philosophical decision at the time of the creation of React, or is there some technical reason, like maybe internal usage of some native function like Object.create in React code, which does a distinction between undefined and null?
undefined means a variable has been declared but has not yet been assigned a value :
var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
null is an assignment value. It can be assigned to a variable as a representation of no value :
var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object
From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Proof :
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
and
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
The difference can be explained with toilet tissue holder:
A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.
A zero value is like a holder with an empty toilet tissue tube.
A null value is like a holder that doesn't even have a tissue tube.
An undefined value is similar to the holder itself being missing.
I think the best practice is to tell the user that your data is still loading, then populate the fields with the real data. This approach has been advocated in various blog-posts. Robin Wieruch has a great write up on how to fetch data, with a specific example on how to handle loading data and errors and I will go through his example here. This approach is generally done in two parts.
- Create an
isLoadingvariable. This is abolean. We initially set it tofalse, because nothing is loading, then set it totruewhen we try to fetch the data, and then back tofalseonce the data is loaded. - We have to tell React what to render given the two
isLoadingstates.
1. Setting the isLoading variable
Since you did not provide any code, I'll just follow Wieruch's example.
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
dataFromApi: null,
};
}
componentDidMount() {
fetch('https://api.mydomain.com')
.then(response => response.json())
.then(data => this.setState({ dataFromApi: data.dataFromApi }));
}
...
}
export default App;
Here we are using the browser's native fetch() api to get the data when the component mounts via the use of componentDidMount(). This should be quite similar to what you are doing now. Given that the fetch() method is asynchronous, the rest of the page will render and the state will be up dated once the data is received.
In order to tell the user that we are waiting for data to load, we simply add isLoading to our state. so the state becomes:
this.state = {
dataFromApi: null,
isLoading: false,
};
The state for isLoading is initially false because we haven't called fetch() yet. Right before we call fetch() inside componentDidMount() we set the state of isLoading to true, as such:
this.setState({ isLoading: true });
We then need to add a then() method to our fetch() Promise to set the state of isLoading to false, once the data has finished loading.
.then(data => this.setState({ dataFromAPi: data.dataFromApi, isLoading: false }));
The final code looks like this:
class App extends Component {
constructor(props) {
super(props);
this.state = {
dataFromApi: [],
isLoading: false,
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch('https://api.mydomain.com')
.then(response => response.json())
.then(data => this.setState({ dataFromApi: data.dataFromApi, isLoading: false }));
}
...
}
export default App;
2. Conditional Rendering
React allows for conditional rendering. We can use a simple if statement in our render() method to render the component based on the state of isLoading.
class App extends Component {
...
render() {
const { hits, isLoading } = this.state;
if (isLoading) {
return <p>Loading ...</p>;
}
return (
<ul>
{dataFromApi.map(data =>
<li key={data.objectID}>
<a href={data.url}>{data.title}</a>
</li>
)}
</ul>
);
}
}
Hope this helps.
It Depends. suppose you are fetching books data from server. here is how to do that.
state = {
books: null,
}
if, your backend api is correctly setup. You will get either empty array for no books or array with some length
componentDidMount(){
getBooksFromServer().then(res => {
this.setState({
books: res.data
})
})
}
Now In Your render method
render() {
const { books } = this.state;
let renderData;
if(!books) {
renderData = <Spinner />
} else
if(books.length === 0) {
renderData = <EmptyScreen />
}
else {
renderData = <Books data = { books } />
}
return renderData;
}
If you are using offline data persistence In that case initially you won't have empty array.So This way of handling won't work. To show the spinner you have to keep a variable loader in state. and set it true before calling api and make it false when promise resolves or rejects.
finally read upon to state.
const {loader} = this.state;
if(loader) {
renderData = <Spinner />
}