Skip to content

Instantly share code, notes, and snippets.

@lamtranweb
Created May 25, 2019 06:51
Show Gist options
  • Select an option

  • Save lamtranweb/66d89fcb1af28ac972df36e10a08e321 to your computer and use it in GitHub Desktop.

Select an option

Save lamtranweb/66d89fcb1af28ac972df36e10a08e321 to your computer and use it in GitHub Desktop.

Revisions

  1. lamtranweb created this gist May 25, 2019.
    49 changes: 49 additions & 0 deletions fetch-with-ts-remote-data.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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);