简体   繁体   中英

Need to render after the function is executed React js

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

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.

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>
          );
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM