0

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.

3

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.