Reputation: 137
I'm trying to get the value of what the user types in a search input , I then want to pass this variable into my endpoint and return the data
<input type="text" class="search" placeholder="planet">
<script>
const media = 'image';
const searchInput = document.querySelector('.search');
searchInput.addEventListener('change', searchData);
//get value of what is typed into search input.
function searchData() {
let search = this.value;
const finalData = getData(search);
}
// pass the search variable into the endpoint in getData function.
function getData() {
const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;
console.log(endpoint);
const result = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => result.push(...data.collection.items));
}
I'm not sure if im doing this correct or if there is an alternative better way i'm still new to JavaScript. Thank you.
Upvotes: 0
Views: 147
Reputation: 5011
Here you go
<input type="text" class="search" placeholder="planet">
<div class="output"></div>
<script>
const media = 'image';
const searchInput = document.querySelector('.search');
const output = document.querySelector('.output')
searchInput.addEventListener('change', searchData);
//get value of what is typed into search input.
async function searchData() {
let search = this.value;
const finalData = await getData(search);
render(finalData);
}
function render(data) {
output.innerHTML = JSON.stringify(data)
}
// pass the search variable into the endpoint in getData function.
function getData(search) {
const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;
return fetch(endpoint)
.then(blob => blob.json())
.then(data => data.collection.items);
}
</script>
fiddle here https://jsfiddle.net/xyhk49wy/
You can modify the render
function so it does something else instead of showing stringified JSON
Upvotes: 1