0

I am relatively new to JavaScript/React. Working on a simple React App, I am stuck with a real problem I cannot figure it out.

This is the code I am talking about:

const Inventory = () => {
   
    let product = [];
 
    let response = fetch("http://localhost:3000/inventory.json")
    .then( response => response.json() )
    .then( data => data.map( item => {

        product.push(item.name);
    
        }))
    .then (console.log(product[0]))

        
    setTimeout( x => console.log(product[0]), 1000)
        

Inventory.json is a simple file, which I will post here for the sake of completeness:

[   
    {
        "name": "Cookies1",
        "details": "Cookies1D",
        "lastFilled": "5. Jan. 2022",
        "lastReq": "2. Jan. 2022",
        "Status": "full"
    },
       
    {
        "name": "Cookies2",
        "details": "Cookies2D",
        "lastFilled": "5. Jan. 2022",
        "lastReq": "2. Jan. 2022",
        "Status": "full"
    }

]

Now, I expected the code to work as follows:

  1. Fetch will get the Data (which works!)
  2. After that the JSON is extracted from the data (first THEN)
  3. After that the JSON is extracted to an array via map (second THEN)
  4. After that the first array-element is console-logged (third THEN)

However, what I get from the console from my third .then is undefined.

To test whether this issue has something to do with the async nature of fetch I added a line that waits 1 second before it console-logs the first array element ( setTimeout(... ), which works absolutely as expected and console.logs "Cookies1".

But how can that be? My understanding is, that .then is executed after the preceeding commands (i.e. after the preceeding promise has been resolved). That means that .then (console.log(product[0])) should give me the same (defined) result as setTimeout( x => console.log(product[0]), 1000).

Why does my third .then return undefined and how can I solve this? It seems I have got something terribly wrong. Could anyone help me with that puzzle. I really get get exasperated with it.

Kind regards Chris

WiWi
  • 41
  • 1
  • 4
  • The third then isn't provided with a function, that's the difference. An expression that is supposed to be evaluated asynchronously should always be wrapped with callback function. There's no way how it can work without it in JS. – Estus Flask Dec 01 '21 at 08:42

0 Answers0