user12140833
user12140833

Reputation: 179

pass specific parameter to a function

I have a function:

getBooks(page, count, authorId){
      return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
        .then(response => {
            return response.data
        })
}

I am implementing search function and in search I pass only the authorId i.e

getBooks(akdjh23)

But on doing this it sets akdjh23 to page. i.e page=akdjh23 but I want authorId=akdjh23

My question is how do I send only authorId during search and page and count on general get request.

Search based on id:

getBooks(id)

Get all books:

get(1, 40) -> page=1, count=40

Upvotes: 3

Views: 74

Answers (3)

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

You could pass an object rather the fixed parameters and destructure it by using ES6 Object destructuring

Example.

getBooks({ page, count, authorId }){
  return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
    .then(response => {
        return response.data
    })
}

getBooks({ authorId: 45});
getBooks({ page: 'abc', authorId: 67});

Upvotes: 2

Gene Sy
Gene Sy

Reputation: 1655

Instead of multiple arguments you can change how getBooks work and pass an object instead

getBooks({ page, count, authorId })

you can now just pass the authorId if you need

getBooks({ authorId: 'authorIdPassed' });

Upvotes: 0

Mahatmasamatman
Mahatmasamatman

Reputation: 1535

getBooks(null, null, id)

should do the trick. Note that your code won't work as page and count in your function will not be defined.

Upvotes: 1

Related Questions