[React] Handle HTTP Errors with React
Unfortunately, sometimes a server request fails and we need to display a helpful error message to the user. In this lesson we’ll handle a promise rejection so we can collect that error information, and we’ll also learn how we can best display manage the state of our request so we have a deterministic render method to ensure we always show the user the proper information based on the current state of our React component.
A common mistake people make is to create a state variable called isLoading
and set that to true
or false
. Instead, we’ll be using a status
variable which can be set to idle
, pending
, resolved
, or rejected
. You can learn more about why this is important from Stop using isLoading booleans.
<body> <div id="root"></div> <script src="https://unpkg.com/react@16.12.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script> <script type="text/babel"> function PokemonInfo({pokemonName}) { const [status, setStatus] = React.useState('idle') const [pokemon, setPokemon] = React.useState(null) const [error, setError] = React.useState(null) React.useEffect(() => { if (!pokemonName) { return } setStatus('pending') fetchPokemon(pokemonName).then( pokemonData => { setStatus('resolved') setPokemon(pokemonData) }, errorData => { setStatus('rejected') setError(errorData) }, ) }, [pokemonName]) if (status === 'idle') { return 'Submit a pokemon' } if (status === 'rejected') { return 'Oh no...' } if (status === 'pending') { return '...' } if (status === 'resolved') { return <pre>{JSON.stringify(pokemon, null, 2)}</pre> } } function App() { const [pokemonName, setPokemonName] = React.useState('') function handleSubmit(event) { event.preventDefault() setPokemonName(event.target.elements.pokemonName.value) } return ( <div> <form onSubmit={handleSubmit}> <label htmlFor="pokemonName">Pokemon Name</label> <div> <input id="pokemonName" /> <button type="submit">Submit</button> </div> </form> <hr /> <PokemonInfo pokemonName={pokemonName} /> </div> ) } function fetchPokemon(name) { const pokemonQuery = ` query ($name: String) { pokemon(name: $name) { id number name attacks { special { name type damage } } } } ` return window .fetch('https://graphql-pokemon.now.sh', { // learn more about this API here: https://graphql-pokemon.now.sh/ method: 'POST', headers: { 'content-type': 'application/json;charset=UTF-8', }, body: JSON.stringify({ query: pokemonQuery, variables: {name}, }), }) .then(r => r.json()) .then(response => response.data.pokemon) } ReactDOM.render(<App />, document.getElementById('root')) </script> </body>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-04-01 [Docker] Building a Node.js Image
2019-04-01 [Algorithm] Delete a node from Binary Search Tree
2019-04-01 [Javascript] Check both prop exists and value is valid
2019-04-01 [Algorithm] Check if a binary tree is binary search tree or not
2016-04-01 [Typescript] Function defination