Check If an Array Is Empty in React Native

this.state return empty array when render

There are basically 2 errors in GetTransaction state assignment:

  1. you can't read a state just assigned because this.setState is async. If you want to get the very last value of state you should use this.setState's callback:

    this.setState({results:response}, () => {
    console.log(this.state.result); //<-- here you have the very last value of result
    });
  2. state must be always setted with this.setState: this.state.series.push(a.count) is not good.

So you have to rewrite your code in this way:

        ...
this.setState({results:response}, () => {
let seriesAppo = [];
this.state.results[0].map((a) => {
seriesAppo.push(a.count);
});
this.setState({series: seriesAppo}, () => {
console.log(this.state.series);
})
});
...

Having trouble checking if an array has data or is empty in ReactJS

Easiest would be to have the default be undefined rather than an empty array. Then in your render check:

  • undefined means its loading
  • empty array means no data, so show message
  • non-empty array you can shown data

{!this.state.offer ? <Loader /> : this.state.offer.length ? <OfferList /> : <span>No data available</span>}

Get non empty items in array map in react native

filter out the empty elements then map over the array filter returns.

Here's a contrived example to show you how it works.

const arr = [undefined, 'Bob', '', 'Sally', 'Joe', '', null, 'Pam'];

// `filter` out the empty/null/undefined elements
// and then `map` over that filtered array
const out = arr
.filter(el => el)
.map(el => `<div>${el}</div>`);

document.body.innerHTML = out.join('');

How to empty an array while i back to my previous screen in react-native?

just declare the "const AccordianArray = [];" in side render() function. It will empty your array every time.

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
// array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach

Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.

    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach

In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}

Or the opposite:

if (array?.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}

Check if array undefined in React component

Check out optional chaining.

link.dataInfo1param1?.length > 0

react js useState array is empty in first time click in the console log

It's not empty on the first click but you can handle it this way :

const addItem = () => {
setItem([
...items,
{
id: items.length,
value: Math.floor(Math.random() * 10) + 1
}
]);
};

React.useEffect(() => {
console.log(items);
}, [items]);

The useEffect hook will console log items after they've been changed so you will see the latest state or in other words the updated and final state .

An empty array is returned when using useState in React

The promise has not been fulfilled yet when you are logging it. try like this

// two useeffect hooks, one for logging, other for populating
useEffect(()=>{
getBookList();
},[]);

useEffect(()=>{
console.log(book);
},[book]);

the whole component might look like this

function Search(){
const [title, setTitle]=useState('');
const [book, setBook]=useState([]);

const onChange=(e)=> setTitle(e.target.value);

const headers= {};
const getBookList= ()=>{
axios.get(`https://dapi.kakao.com/v3/search/book?target=title&query=${title}`, {headers}).then(res => {
setBook(res.data.documents)
})
};

useEffect(()=>{
getBookList()
},[]);

return (
<div>
<input value={title} onChange={onChange}></input>
<button onClick={getBookList}>push</button>
<div>{book.length > 0 ? JSON.stringify(book[0]) : ""}</div>
</div>
);
}

export default Search;

Note: {book.length > 0 ? book[0] : ""} is for checking if the array has been populated, since at the moment the component loads, the request response hasnt arrived yet

Edit: do not render json in the dom, JSON.stringify(book[0]) is the correct way, if you want to see the json data.



Related Topics



Leave a reply



Submit