Created
May 25, 2019 06:51
-
-
Save lamtranweb/66d89fcb1af28ac972df36e10a08e321 to your computer and use it in GitHub Desktop.
fetch-with-ts-remote-data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as React from "react"; | |
| import { render } from "react-dom"; | |
| import RemoteData from "ts-remote-data"; | |
| import "./styles.css"; | |
| import { useState, useEffect, ReactNode } from "react"; | |
| const URL = "https://jsonplaceholder.typicode.com/todos/1"; | |
| interface Todo { | |
| id: number; | |
| userId: number; | |
| title: string; | |
| completed: boolean; | |
| } | |
| type MyTodo = RemoteData<Todo>; | |
| function App() { | |
| const [state, setState] = useState<MyTodo>(RemoteData.NOT_ASKED); | |
| useEffect(() => { | |
| (async () => { | |
| setState(RemoteData.LOADING); | |
| try { | |
| const response = await fetch(URL); | |
| const json = await response.json(); | |
| setState(json); | |
| } catch (e) { | |
| setState(RemoteData.failWith(e)); | |
| } | |
| })(); | |
| }, []); | |
| let State: ReactNode = null; | |
| if (state === RemoteData.LOADING) { | |
| State = <h1>Loading</h1>; | |
| } | |
| if (RemoteData.isReady(state)) { | |
| State = <h1>{state.title}</h1>; | |
| } | |
| if (RemoteData.isFailure(state)) { | |
| State = <h1>{(state.error as TypeError).message}</h1>; | |
| } | |
| return <div className="App">{State}</div>; | |
| } | |
| const rootElement = document.getElementById("root"); | |
| render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment