i want to make a table with JavaScript and i am fetching data from Api so i have created two function and i want to merge these functions in to single #output
. my one function is fetch data from api and render out in table, second is fetch data from Api for filtering the data.
index.js
JavaScript
x
47
47
1
// output of data
2
const Story = document.querySelector('#approvedList');
3
// Create Event Listener
4
document.querySelector('#search-input').addEventListener('keyup', filterPost);
5
6
// Get All Posts Data
7
function getPosts() {
8
9
axios.get('http://localhost:8000/api/approved/')
10
11
// data response
12
.then((res) => {
13
Story.innerHTML = '';
14
res.data.results.map((object) => {
15
Story.innerHTML +=
16
`<tr>
17
<td>${object.id}</td>
18
<td><a href="#" class="detaillink">${object.title}</a></td>
19
<td>${object.author}</td>
20
<td>"${object.created_on}"</td>
21
</tr>`;
22
})
23
})
24
.catch(error => console.log(error))
25
};
26
getPosts();
27
28
// Filtered Data function
29
function filterPost(e) {
30
let value = e.target.value
31
axios.get(`http://localhost:8000/api/approved/?search=${value}`)
32
// data response
33
.then((res) => {
34
Story.innerHTML = '';
35
res.data.results.map((object) => {
36
Story.innerHTML +=
37
`<tr>
38
<td>${object.id}</td>
39
<td><a href="#" class="detaillink">${object.title}</a></td>
40
<td>${object.author}</td>
41
<td>"${object.created_on}"</td>
42
</tr>`;
43
})
44
})
45
.catch(error => console.log(error))
46
}
47
Advertisement
Answer
Basically just do one function that can accept filter and just check if that filter is provided, and if it is – then add to url your parameters. Quick one would be this:
JavaScript
1
31
31
1
// Get All Or Filtered Posts Data
2
function getPosts(filter = null) {
3
let url = 'http://localhost:8000/api/approved/';
4
if(filter) {
5
url += `?search=${filter}`
6
}
7
axios.get(url)
8
9
// data response
10
.then((res) => {
11
Story.innerHTML = '';
12
res.data.results.map((object) => {
13
Story.innerHTML +=
14
`<tr>
15
<td>${object.id}</td>
16
<td><a href="#" class="detaillink">${object.title}</a></td>
17
<td>${object.author}</td>
18
<td>"${object.created_on}"</td>
19
</tr>`;
20
})
21
})
22
.catch(error => console.log(error))
23
};
24
getPosts();
25
26
// Filtered Data event handler
27
function filterPost(e) {
28
let value = e.target.value
29
getPosts(value);
30
}
31