Skip to content

Commit

Permalink
Merge pull request #2264 from breatheco-de/flux
Browse files Browse the repository at this point in the history
Fix example of demo react hooks
  • Loading branch information
alesanchezr authored Apr 25, 2024
2 parents 6950f6c + 8807d9e commit bed46f4
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 20 deletions.
37 changes: 27 additions & 10 deletions src/content/lesson/react-hooks-explained.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,19 +260,36 @@ const Todos = (props) => {
// Inicializa la variable "tasks" como un array vacío y conéctalo a la función setTasks
const [ tasks, setTasks ] = useState([]);

// Esta función useEffect se ejecutará solo una vez, cuando el componente finalmente se cargue por primera vez
useEffect(() =>
// Aquí busco mis todos de la API
fetch('https://assets.breatheco.de/apis/fake/todos/user/alesanchezr')
.then(r => r.json())
.then(data => setTasks(data)) // Aquí se actualiza la variable "tasks" con los datos entrantes
, []);

return <ul>{tasks.map((t, index) => <li key={index}>{t.label}</li>)}</ul>;
// Ésta función encapsula la lógica de traer la lista de todos de la api
// asi como crear una nueva lista si ésta no existe.
const fetchList = async () => {
const endpoint = "https://playground.4geeks.com/todo/users/demo";
let response = await fetch(endpoint);
if (response.ok) {
// Sila lista se recibe, las task son cargadas con los todos
let data = await response.json();
setTasks(data.todos);// Aquí se actualiza la variable "tasks" con los datos entrantes
return response.status;
}
if (response.status == 404) {
// Si la lista no se encuentra, debe ser creada con una petición POST
let newList = await fetch(endpoint, { method: "POST" });
if (newList.ok) setTaks([]);
}
};

// Esta función useEffect se ejecutará solo una vez, cuando el componente finalmente se cargue por primera vez
useEffect(() => {
// here I fetch my todos from the API
fetchList();
},[] // <---- thanks to this empty array the use effect will be called only once
);
return <ul>{tasks.map((t, index) => <li key={index}>{t.label}</li>)}</ul>;
}

```

> ☝ Revisa el código en profundidad y la demostración en vivo [haciendo clic aquí](https://codesandbox.io/s/xenodochial-varahamihira-egh86?fontsize=14).
> ☝ Revisa el código en profundidad y la demostración en vivo [haciendo clic aquí](https://codesandbox.io/p/sandbox/using-the-useeffect-to-load-data-on-component-mount-forked-8gprc3).
## Otras lecturas

Expand Down
38 changes: 28 additions & 10 deletions src/content/lesson/react-hooks-explained.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,19 +261,37 @@ const Todos = (props) => {
// Initialize the "tasks" variable to an empty array and hook it to setTasks function
const [ tasks, setTasks ] = useState([]);

// This useEffect will run only one time, when the component is finally loaded the first time
useEffect(() =>
// Here I fetch my todos from the API
fetch('https://assets.breatheco.de/apis/fake/todos/user/alesanchezr')
.then(r => r.json())
.then(data => setTasks(data)) // Here it re-setted the variable "tasks" with the incoming data
, []);

return <ul>{tasks.map((t, index) => <li key={index}>{t.label}</li>)}</ul>;
// This function encapsulates the logic of fetching the todo list
// and creating a new one if the list doesn't exists
const fetchList = async () => {
const endpoint = "https://playground.4geeks.com/todo/users/demo";
let response = await fetch(endpoint);
if (response.ok) {
// If the list is fetched, the task gets loaded with the todos
let data = await response.json();
setTasks(data.todos);
return response.status;
}
if (response.status == 404) {
// If the list is not found, it must be created with a POST request
let newList = await fetch(endpoint, { method: "POST" });
if (newList.ok) setTaks([]);
}
};

//this function useEffect will run only one time, when the component is finally lodaded the first time.
useEffect(() => {
// here I fetch my todos from the API
fetchList();
},[] // <---- thanks to this empty array the use effect will be called only once
);
return <ul>{tasks.map((t, index) => <li key={index}>{t.label}</li>)}</ul>;
}

```

> ☝ Review the code in depth and check the live demo by [clicking here](https://codesandbox.io/s/xenodochial-varahamihira-egh86?fontsize=14).
> ☝ Review the code in depth and check the live demo by [clicking here](https://codesandbox.io/p/sandbox/using-the-useeffect-to-load-data-on-component-mount-forked-8gprc3).

## Further Reading

Expand Down

0 comments on commit bed46f4

Please sign in to comment.