0

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..

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

2 Answers 2

1

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>

Edit

Example for the commented requests.

import { Clan } from "../clan.jsx"

// App
<div>
   {loading ? "Loading..." : <Clan data={data}/>}
</div>

// New file clan.jsx
export const Clan = (props) => {
  return (
    <div>
         <h1>{props.data.clan.name}</h1>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

5 Comments

yep that worked for the loading part and you using JSON.stringify on data but suppose i have data.troops.level how can i access this in typescript and suppose render that in h1 tag and data.clan.name in h2 tag
I would create another component that takes the data as it's props, and renders each bit of data itself. <h1>{data.clan.name}</h1> etc. Example would be: {loading ? "Loading...." : <Clan data={data}>}
hey can you please edit your answer to showcase this part making new component and passing props to it and using it on elements including loading while fetching too
Done. But id also recommend you watch/read a tutorial on functional react instead of being spoon fed, good luck.
@SuperiorJacob generally it is best to provide a code answer with proper explanation. This is not considered sppon feeding.
1

try this

interface ResponseData {
  id: string
  // other data ...
}
const App = () => {
  const [data, setData] = useState<ResponseData | null>(null)
  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: ResponseData = 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 (
      <div>
        {data.map(d => (
          <div key={d.id}>{d.id}</div>
        ))}
      </div>
    )
  return <div>no data found</div>
}
export default App

4 Comments

Well the loading part is all clear also i am getting error "Property 'id' does not exist on type 'never'" I have too much confusion on this part did i need interfaces and if yes how can i use interface to eliminate this
also a new error where app component is being imported and rendered "App' cannot be used as a JSX component. Its return type 'Element | Element[]' is not a valid JSX element."
well i eliminated the first error by "data.map((d:RootObject) => <div key={d.bestTrophies}>{d.donations}</div>" where RootObject is the interface
you need to define type for response object, update my ans with typescript

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.