N
N
NickForDevelop2020-05-01 10:27:05
JavaScript
NickForDevelop, 2020-05-01 10:27:05

How to check for the existence of data more concisely?

this.loadData().then(response => {
          if (response && response.data && response.data.users && response.data.users.length) {
            this.usersLocal = response.data.users
          }
        })

Very annoying piling up through the dot.
Is there something easier?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-05-01
@NickForDevelop

optional chaining :
if (response?.data?.users?.length) {

S
Sergey Sokolov, 2020-05-01
@sergiks

there are libraries to simplify this task, for example, dot-object
and there is try .. catch
I don't see a problem with checking 4 conditions. You can move line by line:

this.loadData().then(response => {
  if (
    response
    && response.data
    && response.data.users
    && response.data.users.length
  ) {
    this.usersLocal = response.data.users
  }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question