0

I have array initial value is like empty, in fetch function i am updating filterData array with data but outside of fetchData scope it's not updating filterData it's still empty

 // Fetching Data and updating states
    let filterData = []
    const fetchData = async () => {
    const req = await fetch(
         "https://stratic-research-institute.firebaseio.com/articles.json"
          );
    let loaded = [];
    const res = await req.json();
    const vl = Object.keys(res);
    vl.map((item) => loaded.push(res[item]));

    setposts({
    arData: loaded.reverse(),
    loading: false,
   });
   filterData = loaded;
};
 console.log(filterData)
Muhammad Faisal
  • 315
  • 3
  • 14
  • since `fetchData` is async, `console.log(filterData)` executes before your `fetchData` finishes, hence it shows empty array. – Sarthak Aggarwal Apr 07 '20 at 15:14
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Quentin Apr 07 '20 at 15:31
  • https://reactjs.org/docs/faq-ajax.html – Quentin Apr 07 '20 at 15:31

3 Answers3

1

You are not calling the function in the code call fetchdata and use promise to print the value of filter data

let filterData = []
    const fetchData = async () => {
      const req = await fetch(
        "https://stratic-research-institute.firebaseio.com/articles.json"
      );
      let loaded = [];
      const res = await req.json();
      const vl = Object.keys(res);
      vl.map((item) => loaded.push(res[item]));

     
      filterData = loaded;
    };
    fetchData().then(()=>{
      console.log(filterData)
    })
Bilal Hussain
  • 572
  • 6
  • 14
0

The filterData is inside the scope.

The console.log is executing before the fetch() as the fetch() is an async method.

0

You can try something like this because you are accessing asynchronous data... Also you can't use await outside an async function.

// Fetching Data and updating states
    const fetchData = async () => {
      const req = await fetch(
           "https://stratic-research-institute.firebaseio.com/articles.json"
            );
      let loaded = [];
      const res = await req.json();
      const vl = Object.keys(res);
      vl.map((item) => loaded.push(res[item]));
      // don't have the whole context so let's comment this
     /* setposts({
      arData: loaded.reverse(),
      loading: false,
     }); */
     return loaded
  };
// one option
const run =  async() => {
  const filteredData = await fetchData();
  console.log(filteredData);
}
run();
// other option
fetchData().then((r)=>console.log(r))
Julio Vásconez
  • 308
  • 5
  • 11