skip to Main Content

Here i am trying get a data from the url using axios. I am getting a data when i console log response.data
this is the log i get but when i try console log response.data.trees then it shows undefined. How can i solve this issue.

Fetch1 {
  "trees": [
    {
      "id": 1,
      "name": "Baobab",
      "species_name": "Adansonia",
      "image": {
        "src": "https://upload.wikimedia.org/wikipedia/commons/3/36/Baobab_Adansonia_digitata.jpg",
        "alt": "A large African baobab tree with bright green leaves against a soft blue sky."
       }
    },
    {
      "id": 2,
      "name": "Red Mangrove",
      "species_name": "Rhizophora mangle",
      "image": {
        "src": "https://upload.wikimedia.org/wikipedia/en/1/16/Red_mangrove-everglades_natl_park.jpg",
        "alt": "A free-standing red mangrove tree growing in shallow water in the backcountry of the Cape Sable area of Everglades National Park.",
      }
    }
  ]
}

Fetch2 undefined
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('url');
        setTrees(response.data.trees);
        console.log('Fetch1',response.data)
        console.log('Fetch2',response.data.trees)
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

2

Answers


  1. The response you are receiving from the API is in JSON format. It is not an object. In order for you use it like an object like you expect, use let data = JSON.parse(response.data) and then do data.trees to access the element you want.

    You can read more about JSON.parse() here.

    Hope this helps!

    Login or Signup to reply.
  2. he response you are receiving from the API is in JSON format. It is not an object. In order for you use it like an object like you expect, use let data = JSON.parse(response.data) and then do data.trees to access the element you want.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search