0

I am trying to fetch some data from API gateway and use that to render a tree but i'm not able to do so. Here is what i am trying

var structure = [

];

export default function App() {
  
  React.useEffect(() => {
    
    async function fetchData() {
      const res = await axios.get(`Some API_GATEWAY Request`)
      structure.push(JSON.parse(res['data']))
      console.log(structure[0])
    }
    
    fetchData();
    console.log(structure[0])
  }, []);

  return (
    <div className="App">
      {console.log(structure[0])}
      <Tree data={structure} />
    </div>
  );
}

Here the output is

undefined //from 3rd console.log
undefined //from 2nd console.log
some value //from 1st console.log

how to get the value inside the return so that i can use the strucutre

4
  • 1
    fetchData().then(() => { console.log(structure[0]); }) will show some value and to have it rendered you need a reference. Basically fetchData is asynchronous but you are accessing structure[0] before it gets populated which is ... asynchronously. Commented Jan 21, 2021 at 8:32
  • @AndreaGiammarchi can you please show how to render it Commented Jan 21, 2021 at 8:39
  • @AndreaGiammarchi can you show some example on how to render it using reference I have never used it Commented Jan 21, 2021 at 8:56
  • blog.logrocket.com/a-guide-to-react-refs Commented Jan 21, 2021 at 9:09

2 Answers 2

1
import React, { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
  const [catties, setCatties] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetchCats = async () => {
    setLoading(true);
    const res = await axios.get("https://api.thecatapi.com/v1/images/search");
    setLoading(false);
    setCatties([...catties, ...res.data]);
  };

  useEffect(() => {
    fetchCats();
  }, []);

  if (loading) {
    return <h1> ...loading</h1>;
  }

  return (
    <div>
      {catties.map(el => (
        <img src={el.url} alt="Catty" key={el.id} />
      ))}
    </div>
  );
};

export default App;

Run this code in codesandbox, you will see how it works. This is a standrat clean way of doing this. Usually you want to keep these kind of functions inside of redux or context. Please let me know if this worked for you.

Sign up to request clarification or add additional context in comments.

Comments

0

2 things you can do:

  1. make structure array a part of your state:
  2. You can create that function above useEffect, and call it inside. So code will look like this:
 export default function App() {
       const [structure, setStructure] = React.useState([]);
       async function fetchData() {
           const res = await axios.get(`Some API_GATEWAY Request`)
           setStructure(JSON.parse(res['data']))
            console.log(structure[0])
       }                
          React.useEffect(() => {    
            fetchData();
          }, []);            
          return (
            <div className="App">
              {console.log(structure[0])}
              <Tree data={structure} />
            </div>
          );
        }

3 Comments

I tried this but it never executed the fetchData function
can you please provide your api which you are trying to call? I will try too and send back the result
sorry but i can't provide you that API

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.