2

I have the code below

import React from 'react';
import axios from 'axios'

//let termExample = "https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=5&gsrsearch='New_England_Patriots'";

function APIThing({ term }) {

    let wikioutput = []

    axios.get(term).then((response) => {for (let i in response.data.query.pages) if(wikioutput) wikioutput.push(response.data.query.pages[i])})
        
    function safe(x){
        console.log("test", x[0], x)
        if (x[0]){
          console.log("test2", x[0], x[0].title)
          return x[0].title
        }
    }

    return (
        <>
            <p>TEST {safe(wikioutput)} TEST</p>
            <p>EXAMPLE {safe([{title: "Test"}])}</p>
        </>
    )
}


export default APIThing;

When term is a wikipedia api url, I cannot return the value of wikioutput[0]. When I log wikioutput (or x in this case) I can see the entire array of objects, but x[0] returns undefined

  • 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) – tkausl Apr 18 '21 at 18:54
  • @tkausl unfortunately no, I /can/ see the whole array, but when I log array[0] it's undefined – thejonymyster Apr 18 '21 at 18:58
  • __Where__ exactly do you see the whole array? Where did you put the console.log? – tkausl Apr 18 '21 at 19:02
  • Your functional component is wrong - [learn](https://reactjs.org/docs/hooks-overview.html) how to work with `hooks` for state management in `react.js` and how to make asynchronous calls inside a functional component. – goto Apr 18 '21 at 19:05
  • @tkausl the log occurs on line 13, and here's the result in the console [link](https://imgur.com/a/GT5Dzfq) – thejonymyster Apr 18 '21 at 19:14
  • This log output is misleading, Chrome is trying to be nice to you. Try `JSON.stringify(x)` and you'll see that your array is empty when it hits this line. – tkausl Apr 18 '21 at 19:15

3 Answers3

1

I came across this post when I looked for an explanation for my very similar problem. I also have an asynchronous API call that gives me an array with several objects.

`useEffect(() => {
    async function fetchMailContent() {
      const response = await fetch(insertapiwebsitehere.com;
      if (open) {
        try {
          const res = await response.json();
          setMailContent(res);
          setLoading(false);
        } catch (err) {
          console.error(err);
          setError(true);
          setLoading(false);
        }
      }
    }
    fetchMailContent();
}, [open]);`

The array I get from this is then given to another function where I attempted to place a value of one of the array's objects into a textfield component.

`export function MainTab(){
    [shortened]
    return(
        <TextField variant={'outlined'} type="text" value={array[0].field_entry} />
    )
}`

This would then result in the error of thejonymyster: array[0] is undefined. But a console.log(array[0]) would work fine and gave me the right object. The fix is indeed rooted in the asynchronicity. You need to ask first if the object value exists before rendering it. This can be done with a simple ? after the array[0] and fixed the issue for me. So the Textfield component looks like this:

<TextField variant={'outlined'} type="text" value={array[0]?.field_entry} />

  • I'm definitely never coming back to this specific project but thank you so much for your response. I hope your answer can help people for decades to come :D – thejonymyster Jun 29 '22 at 15:30
  • 1
    That was kind of the intention because your question ist the first entry to pop up on Google :D maybe someone will find this useful. – ThatOneWithTheHat Jun 30 '22 at 14:35
0

You should really be using hooks + useEffect in ReactJS that will most likely fix your problem, you can find examples here

Maxime Ghéraille
  • 1,465
  • 3
  • 16
  • 31
0

what i ended up doing was json stringifying the array and regexing for the first element. json stringify array didnt give empty, miraculously. if anyone knows why array existed but array[0] didnt, id love to know someday. link to this post

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 02 '21 at 03:31
  • 1
    im not sure what i should do about that. i kind of just wanted to report back on what i ended up doing for posterity, i dont rlly have any interest in continuing this rigorously – thejonymyster Nov 02 '21 at 03:38
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 02 '21 at 06:14