Home > database >  Render fetched API json object in react component Typescript
Render fetched API json object in react component Typescript

Time:08-07

here is my initial code where i tried to render component from data received from api

i have my json received from api call and is saved in the state "data"

i want to show a loading screen while api is being fetched like i have a state for that too "Loading"

Loading ? Then render data on elements : Loading..

But i am unable to figure out the proper implementation in Typescript

const App = () => {
  const [data, setData] = useState([]);
  const [Loading, setLoading] = useState(false);

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

  const Fetchapi = async () => {
    try {
      await axios.get("http://localhost:8081/api").then((response) => {
        const allData = response.data;
        setData(allData);
      });
      setLoading(true);
    } catch (e) {
      console.log(e);
    }
  };
  
//i have my json received from api call and is saved in the state "data"
//i want to show a loading screen while api is being fetched like i have a state for that too  "Loading"
// Loading ? Then render data on elements : Loading..
// But i am unable to figure out the proper implementation in Typescript 




  return (
    <div>
             i need my json object rendered here i tried map method on data and i am 
             getting errors and i have my json2ts interfaces imported in this 

    </div>
  );
};
export default App;

CodePudding user response:

try this

const App = () => {
  const [data, setData] = useState([])
  const [Loading, setLoading] = useState(true)

  useEffect(() => {
    Fetchapi()
  }, [])

  const Fetchapi = async () => {
    try {
      setLoading(true) // USE BEFORE FETCH
      await axios.get("http://localhost:8081/api").then(response => {
        setLoading(false) // SET LOADING FALSE AFTER GETTING DATA
        const allData = response.data
        setData(allData)
      })
    } catch (e) {
      setLoading(false) // ALSO SET LOADING FALSE IF ERROR
      console.log(e)
    }
  }

  if (Loading) return <p>Loading...</p>
  if (data?.length) return data.map(d=><div key={d.id}>{d.id}</div>)
  return <div>no data found</div>
}
export default App

CodePudding user response:

I would camelCase your values/functions and move your fetchApi into the effect itself, as currently its a dependency.

Put setLoading(true) above your fetch request as currently it's not activating until the fetch goes through.

Then below it put setLoading(false), and also inside of your catch.

In your return statement you can now add something like this:

<div>
   {loading ? "Loading..." : JSON.stringify(data)}
</div>
  • Related