Guest User

app.txs

a guest
Aug 14th, 2022
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { useState, useEffect } = React;
  2.  
  3. interface ITodo {
  4.   userId: number;
  5.   id: number;
  6.   title: string;
  7.   completed: boolean;
  8. }
  9.  
  10. // App.tsx
  11. function App() {
  12.   const [todos, setTodos] = useState<ITodo[]>([]);
  13.  
  14.   useEffect(() => {
  15.     fetch("https://jsonplaceholder.typicode.com/todos/1")
  16.       .then((response) => response.json())
  17.       .then((res) => {
  18.         if (Array.isArray(res)) {
  19.           return setTodos(res);
  20.         }
  21.         // The API only returns an object when getting a single item.
  22.         // Therefore, we add that object to an array, as to keep our
  23.         // render logic the same.
  24.         if (typeof res === "object" && !Array.isArray(res)) {
  25.           return setTodos([res]);
  26.         }
  27.       });
  28.   }, []);
  29.  
  30.   return (
  31.     <div>
  32.       {todos.length > 0 &&
  33.         todos.map(({ userId, id, title, completed }) => (
  34.           <div key={id}>
  35.             <p>
  36.               <span className="text-danger">Todo id:{id}</span>Title: {title}
  37.               <input type="checkbox" checked={completed}></input>
  38.             </p>
  39.           </div>
  40.         ))}
  41.     </div>
  42.   );
  43. }
  44.  
  45. ReactDOM.render(<App />, document.body);
  46.  
Advertisement
Add Comment
Please, Sign In to add comment