0

I have the following function component in React:

function GetData() {
  const [randomDataJSON, setRandomDataJSON] = useState('');
  const url = 'https://randomuser.me/api/';

  const getData = () => {
    axios
      .get(`${url}`)
      .then((results) => {
        const userData = results.data.results;
        setRandomDataJSON(JSON.stringify(userData, null, 2));
      })
      .catch((err) => console.error(err));
  };

  return (
    <div>
      <h3>GetData Component</h3>
      <pre>{randomDataJSON[0].name.first}</pre>
      <button onClick={getData}>Get Data</button>
    </div>
  );
}
export default GetData;

The JSON data from the API is as follow:

[
  {
    "gender": "female",
    "name": {
      "title": "Miss",
      "first": "Barbara",
      "last": "Sullivan"
    }, 
...

I would like to access and display the first name of the JSON data from the API by using {randomDataJSON[0].name.first in the <pre> tag. However, I keep getting the following error message: TypeError: Cannot read properties of undefined (reading 'name')

2
  • it seems the problem is in you state const [randomDataJSON, setRandomDataJSON] = useState(''); it should be const [randomDataJSON, setRandomDataJSON] = useState([]); the default state should be an array not a string. try it out. also try to see what is the content in the response from axios. Commented Oct 30, 2021 at 7:43
  • @BobWhite, I don't think there is requirements for default value in react. Also don't think there is a need for useEffect there. Commented Oct 30, 2021 at 7:46

3 Answers 3

2

You are setting json string to randomDataJSON state variable, and trying use JSON string as an object. You can try to console.log(randomDataJSON) to confirm my suspicions.

I think you should not convert your data object to json in first place, so setRandomDataJSON(JSON.stringify(userData, null, 2)); will be setRandomDataJSON(userData);

function GetData() {
  const [randomData, setRandomData] = useState('');
  const url = 'https://randomuser.me/api/';

  const getData = () => {
    axios
      .get(`${url}`)
      .then((results) => {
        const userData = results.data.results;
        setRandomData(userData, null, 2);
      })
      .catch((err) => console.error(err));
  };

  return (
    <div>
      <h3>GetData Component</h3>
      <pre>{randomData[0].name.first}</pre>
      <button onClick={getData}>Get Data</button>
    </div>
  );
}
export default GetData;
Sign up to request clarification or add additional context in comments.

7 Comments

you should not set string because you have to parse reverse in order to use as object
@BobWhite, in post question he is using JSON.stringify, which is converting object to string. Axios on the other hand is automatically converting json response to javascript object. So I believe there is no need for either JSON.parse or JSON.stringify
yep, but it should be that way. json.stringify should be removed. I think the request is waiting for json response. just save the response to state as an array then use it.
@BobWhite, well, isn't that what I have said in my answer?
@BobWhite, ok, good point
|
0

At the time the page loads axios wouldn't have ran to request the array so randomDataJSON is a string at that time. You could do

const [randomDataJSON, setRandomDataJSON] = useState([]);

Above you set it to an empty array then check if it has length

<pre>{randomDataJSON.length > 0 && randomDataJSON[0].name.first}</pre>

Comments

0

Thank you very much to everyone pointing me in the right direction. My new code is as follow. My problem was I didn't know React doesn't allow you to render Javascript Object. To fix this, I just use the map() method to map through the data and display the properties in the object.

function GetData() {
  const [randomDataJSON, setRandomDataJSON] = useState([]);
  const url = 'https://randomuser.me/api/';

  const getData = () => {
    axios
      .get(`${url}`)
      .then((results) => {
        const userData = results.data.results;
        setRandomDataJSON(userData);
      })
      .catch((err) => console.error(err));
  };

  console.log('It is an', typeof randomDataJSON);
  console.log('randomDataJSON is ', randomDataJSON);

  return (
    <div>
      <h3>GetData Component</h3>
      {randomDataJSON.map((data) => {
        return <p>{data.name.first}</p>;
      })}
      <button onClick={getData}>Get Data</button>
    </div>
  );
}
export default GetData;

Comments

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.