Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { useState, useEffect } = React;
- interface ITodo {
- userId: number;
- id: number;
- title: string;
- completed: boolean;
- }
- // App.tsx
- function App() {
- const [todos, setTodos] = useState<ITodo[]>([]);
- useEffect(() => {
- fetch("https://jsonplaceholder.typicode.com/todos/1")
- .then((response) => response.json())
- .then((res) => {
- if (Array.isArray(res)) {
- return setTodos(res);
- }
- // The API only returns an object when getting a single item.
- // Therefore, we add that object to an array, as to keep our
- // render logic the same.
- if (typeof res === "object" && !Array.isArray(res)) {
- return setTodos([res]);
- }
- });
- }, []);
- return (
- <div>
- {todos.length > 0 &&
- todos.map(({ userId, id, title, completed }) => (
- <div key={id}>
- <p>
- <span className="text-danger">Todo id:{id}</span>Title: {title}
- <input type="checkbox" checked={completed}></input>
- </p>
- </div>
- ))}
- </div>
- );
- }
- ReactDOM.render(<App />, document.body);
Advertisement
Add Comment
Please, Sign In to add comment