score:0
this is how i usually implement things when it comes to http requests.
this is assuming that you're not using server side rendered (ssr) service like next.js, where you want the data to be fetched before the page is even rendered, then you would use a different approach.
otherwise you could show a loading animation or just show a blank screen until the data is loaded.
click the "run code snippet" button below to see it work.
// main.js
const { usestate, useeffect } = react;
const app = () => {
const [loading, setloading] = usestate(true);
const [error, seterror] = usestate(null);
const [data, setdata] = usestate(null);
useeffect(() => {
/*
stackoverflow not letting me do async/await so doing a promise
*/
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
setdata(json);
setloading(false);
})
.catch(error => {
console.log('error', error);
seterror(error);
setloading(false);
});
}, []);
return <div>
{loading
? <p>loading...</p>
: <div>
{error
? <div>{json.stringify(error)}</div>
: <div>loaded <br />{json.stringify(data)}</div>
}
</div>}
</div>
}
reactdom.render(<app />, document.queryselector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
score:0
since the call to your api is async you will need to wait for the call to be finished to show your app, useeffect
is a good way to do it, but you will need to make some changes in your code to work.
i see that you are handling all the state variables separately but some of them depend on each other, for this cases is better to use an object so you can be sure all the properties are updated at the same time and also to know if you have already the needed data to show your app
// show your app until this is not null
const [state, setstate] = usestate(null);
// set all the state variables at the same time
useeffect(() => { axios.get(url).then(config => setstate(config)) })
if(!state) return <div>loading...</>
return <div>app</div>
another alternative is to use another state variable to control if you should show your app or not
// all your state variables
const [state, setstate] = usestate(null);
.
.
const [isloading, setisloading] = usestate(false);
// set all the state variables at the same time
useeffect(() => {
setlisloading(true);
axios.get(url).then(config => {
setisloading(false);
setstate(config);
)
})
if(isloading) return <div>loading...</>
return <div>app</div>
Source: stackoverflow.com
Related Query
- trying to get config from backend to react front-end
- req.query from backend turns out to be json on React front end after deployed to heroku, how to fix it?
- Download files from GridFS Stream NodeJS Backend / React Front End
- Cannot Post to backend Flask from Front End React Form
- Node application interactively get user input from react front end by pausing the current execution
- How to get params from url with React front end and express backend?
- How to pass data from React front end Hooks to Express backend
- How to use axios from react front end to get object from nodejs on component load (useEffect)
- Integration testing of React front end with Django REST backend
- React Microfronends: How do I pass authentication and other information from one Front end app to another Front end app?
- Django Rest Framework and React Front End: How to prevent unauthorized users from viewing private images if they get a hold of the image URL?
- Issues connecting to my Node.js and MongoDB backend using a React and axios front end
- Data from my react front end not getting to mysql database
- React Js front end and Express backend - can't load static files properly
- how to get config data from appsettings.json with asp.net core & react
- How to deploy React front end + Rails api backend with nginx, capistrano and passenger
- Data from the backend is not appearing when you assign it into new object on the front end
- How to get the response data from backend to React in React-dropzone-uploader
- Error sending POST from React front end to Django,error status 401
- JSX question with ahref tags. Different text input int the backend and need it to render on the react front end as a hyperlink
- Display an image file from Spring boot backend in javascript front end
- Proxy request error when trying to send post request from React to Node, proxy is working fine on get requests
- React axios GET null data from Flask backend
- Trying to get API data from backend to frontend
- I get this error when trying to connect to a graphcool relay API from a react app: Module build failed: Error: No valid GraphQL endpoint
- What should I use to make API requests to my node back end from my React front end?
- I am trying to retreive data from data from django backend to react but keep getting TypeError: get() missing 1 required positional argument: 'pk'
- React front end connects to the development server on my computer instead of the Node server on Azure VM where it is hosted from why using localhost
- How to get data from the backend that needs authorization using React
- How can I add fields to a json file from the fields in the front end in a react application?
More Query from same tag
- How do I add axios to react-redux-universal-hot-example starter kit?
- How can I remove the class="form-control" that comes by default the FormControl component in React-Bootstrap
- Returning all of the specified integers from a string into an array
- Simplify toggle and setState updated item's property
- Login process using Reactjs, Axios and local JSON file
- React component function on disabled prop never called
- Array.push is empty outside while loop
- Webpack-dev-server showing directory list instead of the app page
- React form input won't let me change value
- Empty Mime-type while uploading file in React js application in Windows OS
- Show points on map with leaflet
- ReactJS cannot seem to call function after page load
- Unable to deploy my React App to GitHub properly
- Extending react component received by redux connect()
- When accessing a state variable from a useCallback, value is not updated
- Trying to set state for individual todo items and have them maintain and toggle between 3 colors on click
- Change component's props onClick
- Material UI Autocomplete - Disable listbox after the item selection
- What's the alternative to ComponentDidMount in React Server Rendered Application?
- Apollo Client Reactive variables - not trigger re render after updating the value
- React add property to immutable object
- What is the diffecence between these two if-else block and conditional operator block?
- Why is my onClick being called on render? - React.js
- change input based on props or state in react
- How to give api call once and remove the event listener, once you reached the bottom of page?
- How to make 3 column grid with map function react
- Focus on Input when DIV is clicked
- Firestore query with empty string , 'any' or 'all'
- browser's localstorage keeps resetting to undefined
- How to handle "Cannot read property 'node' of null" in a query