0

I have list of categories. each category is like this:

{
 id,
 name,
 info
}

I want to loop through the list and change eat category's info after a http get request. i have searched and read the similar questions but nothing is working. the info always have it's initial value

3
  • 2
    Please can you share the code Commented May 8, 2021 at 9:58
  • Please provide a minimal reproducable example Commented May 8, 2021 at 10:04
  • Provide the code please, or you can use sandbox for your code. Commented May 8, 2021 at 10:05

2 Answers 2

1

In the snippet below:

  • I am simply looping through the categories array and after the data has been fetched I am updating the info property.

NOTE:

  • A common mistake here could be that you're logging the categories array before the async task is completed.

  • So, in the code below if I replace getData().then(() => console.log(categories)); by getData(); console.log(categories); then I would not see the updated value of info.

const categories = [
  {
    id: 1,
    name: "delectus aut autem",
    info: "not fetched",
    url: "https://jsonplaceholder.typicode.com/todos/1",
  },
  {
    id: 2,
    name: "quis ut nam facilis",
    info: "not fetched",
    url: "https://jsonplaceholder.typicode.com/todos/2",
  },
];

const getData = async () => {
  for (let cat of categories) {
    const res = await fetch(cat.url);
    const json = await res.json();
    cat.info = "fetched";
  }
};

getData().then(() => console.log(categories));

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

2 Comments

@SalehRezaei Please check if this solves your problem, do let me know if you have any issues.
thanks, you answer is exactly what i needed.
0

You can use forEach like below:

arr.forEach(function(part, index) {
  this[index] = "hello world";
}, arr); // use arr as this

1 Comment

There’s no need to pass arr as the this value. The callback function already gets called with the iterated array as its third argument. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.