Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix example of demo react hooks #2264

Merged
merged 2 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading