0

First time using Stack Overflow, sorry if I do something wrong.

I'm building a simple app that allows you to enter a characters name from Rick and Morty, and then build a small card that displays that characters name, a pic of the char, their status, and their current location.

I currently can get the input from the input field and send that data to the API no problem. my issue is getting the data back from the API and setting it to a variable so I can then extract each individual piece of info from the API. i.e. character.name , character.location, etc...

Here's my JavaScript so far:

        // UI variables
    const input = document.getElementById("searchChar");
    
    // Event Listeners
    input.addEventListener("keyup", (e) => {
      const userText = e.target.value;
    
      if (userText !== "") {
        let response = fetch(
          `https://rickandmortyapi.com/api/character/?name=${userText}`
        )
          .then((res) => res.json())
          .then((data) => console.log(data));
      }
    });

I can't return the 'data' or set it to a variable from the .then(data), so how do I get it to use it elsewhere in my code?

Any help is appreciated. I'm new to the Fetch API. Thank you so much!

1 Answers1

0

Updated the answer based on below suggestions in comments.

Many people use this: which is an anti-pattern, What is the explicit promise construction antipattern and how do I avoid it?

Not to Use: You can wrap your fetch call in a promise and return as a promise.

as an example

function testfunction(arg1, arg2) {
  return new Promise((resolve, reject) => {
    fetch(apiPath)
      .then(resp => {
        if (resp.ok) return resp.json()
      })
      .then(resp => resolve(resp)).catch(err => {
        reject(err)
      })
  })
}

Calling the same from anywhere from your application

testfunction(arg1, arg2)
      .then(result=> {
         // here you can use the API result
      })
      .catch(error => {
        throw error;
      });

This is how you can call your fetch API method and use it at all the places:

function testfunction(arg1, arg2) {
    const request = baseApi.InitialiseGetRequest();    
    return fetch(apiPath).then(resp => {
        if (resp.ok) return resp.json()
      })
      .then(resp => resolve(resp)).catch(err => {
        reject(err)
      })
  }

This is how you can use it accross the application:

testfunction(arg1, arg2)
      .then(result=> {
         // here you can use the API result
      })
      .catch(error => {
        throw error;
      });
KushalSeth
  • 3,265
  • 1
  • 26
  • 29
  • It's already a promise – Quentin Jul 10 '20 at 19:40
  • correct FetchAPI is promise. but we are wrapping the FetchAPI inside a promise so that we can use the method anywhere. You can use testfunction(arg1, arg2).then() anywhere in your application to get the access of your fetchapi method. – KushalSeth Jul 10 '20 at 19:43
  • 1
    You can return the return value of `fetch` and use it "anywhere" (except you can't because its inside an event handler callback function). You're just implementing this anti-pattern: https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it – Quentin Jul 10 '20 at 19:44
  • thanks @Quentin your suggestion is helpful, I am updating my answer, mentioning what not to use and what to use. – KushalSeth Jul 10 '20 at 19:57