how can I take only the data and values that I want from API with 'fetch'

Viewed 28

I have for example API that returns 3 values like name and age and country, I want to fetch the API and store name in a variable.

3 Answers

i assuming your response like these :

apiResponse = {name: tlemcani, age: 28, county: algeria};
let name = apiResponse.name;

Fetch usually returns Promise. You can access your response inside the then() method and store it in a variable like this:

let name;
fetch('/endpoint', options)
  .then(response => response.json())
  .then(data => {
    name = data.name; // storing the name from the API response to the 'name' variable
  })
  .catch(error => {
    console.error("Error:", error);
  });

Assuming the below is the response from the API:

{name: "dummyname", age: 18, county: "US"}

Considering your API response is like this:

{ "name": "john", "age": 21, "country": "US" }

You can parse like following:

// notice async, This should be run in async context. due to use of await keyword
// If you can't use async, use Promise.then(callback) pattern instead.
async function apiRequestHandler() {
  // fetch data from url. returns Promise, resolving with await keyword
  const data = await fetch("https://your-api-endpoint/to/the/path");

  // get json. returns Promise, resolving with await keyword
  const json = await data.json();

  // get each name, age and country
  const { name, age, country } = json;
}
Related