-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 10aeef1
Showing
5 changed files
with
114 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
# ![alt text](https://assets.breatheco.de/apis/img/images.php?blob&random&cat=icon&tags=breathecode,32) Segunda parte de la TODO List, agregando fetch | ||
|
||
Este ejercicio está destinado a ser completado después de la [aplicación de la TODO List](https://projects.breatheco.de/d/todo-list#readme) porque la primera parte es el boilerplate perfecto para comenzar a usar API's. | ||
|
||
Para esta segunda parte, sincronizaremos nuestra lista de tareas con una base de datos real, usando la siguiente [RESTful](http://content.breatheco.de/lesson/understanding-rest-apis) y API pública realizada para este ejercicio. | ||
|
||
🔗 Click aquí para acceder a la [documentación de la API del TODO-list ](http://assets.breatheco.de/apis/fake/todos/). | ||
|
||
Todo este ejercicio se trata de la programación de asincrona porque las interacciones `from` y` to` del servidor deben realizarse de forma asíncrona. De esa manera, el usuario no tiene que esperar a que llegue la información. | ||
|
||
## Instrucciones: | ||
|
||
- Haz que tu TODO List se sincronice con la API de backend cada vez que se agregue o elimine una tarea. | ||
- Agregue un botón de limpieza de todas las tareas que eliminará toda la lista del servidor y actualizará la lista vacía en el front-end. | ||
|
||
Hay 3 momentos críticos en la línea de tiempo de la aplicación (denominado El tiempo de ejecución) para centrarse en su integración: | ||
- **Después de que la lista se carga vacía por primera vez (componentDidMount)**: debes obtener (GET) los datos de la API y actualizar las tareas cuando la información finalmente llegue. | ||
- **Cuando se agrega una nueva tarea**: debes PONER (PUT) la nueva lista en el servidor. | ||
- **Cuando se elimina una tarea**: Debes PONER (PUT) la nueva lista en el servidor. | ||
|
||
## Pista | ||
|
||
Utilice la siguiente fetch call para sincronizar tus tareas con el servidor cada vez que haya un cambio en la lista. | ||
|
||
```js | ||
fetch('http://assets.breatheco.de/apis/fake/todos/user/alesanchezr', { | ||
method: "PUT", | ||
body: JSON.stringify(todos), | ||
headers: { | ||
"Content-Type": "application/json" | ||
} | ||
}) | ||
.then(resp => { | ||
console.log(resp.ok); // Será true (verdad) si la respuesta es exitosa. | ||
console.log(resp.status); // el código de estado = 200 o código = 400 etc. | ||
console.log(resp.text()); // Intentará devolver el resultado exacto como cadena (string) | ||
return resp.json(); // (regresa una promesa) will try to parse the result as json as return a promise that you can .then for results | ||
}) | ||
.then(data => { | ||
//Aquí es donde debe comenzar tu código después de que finalice la búsqueda | ||
console.log(data); //esto imprimirá en la consola el objeto exacto recibido del servidor | ||
}) | ||
.catch(error => { | ||
//manejo de errores | ||
console.log(error); | ||
}); | ||
``` | ||
|
||
Para cualquier otra solicitud, debes seguir cambiando las variables en el fetch:El URL, el método y el payload (carga útil). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
# Second Part of the TODO list, adding fetch | ||
|
||
This exercise is meant to be completed after the [TODO list react application](https://projects.breatheco.de/d/todo-list#readme) because the first part its the perfect boilerplate to start using API's. | ||
|
||
For this second part, we will sync our todo list with a real database, using the following [RESTful](https://content.breatheco.de/lesson/understanding-rest-apis) and public API made for this exercise. | ||
|
||
🔗 Click here to access to the [TODO-list API documentation](http://assets.breatheco.de/apis/fake/todos/). | ||
|
||
This whole exercise is about asynchronous programming because the interactions `from` and `to` the server need to be done async. That way the user does not have to wait for the information to arrive. | ||
|
||
## 📝 Instructions: | ||
|
||
- Make your to-do list sync with the backend API every time a task is added or deleted. | ||
- Add a clean all tasks button that will delete the entire list from the server and update the empty list on the front-end. | ||
|
||
There are 3 critical moments in the application timeline (a.k.a. The runtime) to focus on your integration: | ||
- **After the list loads empty for the first time (componentDidMount)**: you should fetch (GET) the data from the API and update the tasks when the information finally arrives. | ||
- **When a new task is added**: You should PUT the new list on the server. | ||
- **When a task is deleted**: You should PUT the new list on the server. | ||
|
||
## 💡 Hint | ||
|
||
Use the following fetch call to synchronize your tasks with the server every time there is a change on the list. | ||
|
||
```js | ||
fetch('https://assets.breatheco.de/apis/fake/todos/user/alesanchezr', { | ||
method: "PUT", | ||
body: JSON.stringify(todos), | ||
headers: { | ||
"Content-Type": "application/json" | ||
} | ||
}) | ||
.then(resp => { | ||
console.log(resp.ok); // will be true if the response is successfull | ||
console.log(resp.status); // the status code = 200 or code = 400 etc. | ||
console.log(resp.text()); // will try return the exact result as string | ||
return resp.json(); // (returns promise) will try to parse the result as json as return a promise that you can .then for results | ||
}) | ||
.then(data => { | ||
//here is were your code should start after the fetch finishes | ||
console.log(data); //this will print on the console the exact object received from the server | ||
}) | ||
.catch(error => { | ||
//error handling | ||
console.log(error); | ||
}); | ||
``` | ||
|
||
For any other request, you have to keep changing the same variables on the fetch: The URL, the method and the payload. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
{ | ||
"title" : "Todolist Application Using React and Fetch", | ||
"slug" : "todo-list-react-with-fetch", | ||
"status": "published", | ||
"solution": "https://bitbucket.org/codingacademy/todo-list", | ||
"difficulty": "beginner", | ||
"duration" : 8, | ||
"preview": "", | ||
"syntax": "react.js", | ||
"technologies": ["react.js", "fetch-api", "api"], | ||
"translations": ["es", "us"], | ||
"description" : "Create a simple todo web app using the React.js framework and use the API to sync with the server", | ||
"talents": [ | ||
{ "badge": "tag-master", "points": 10 } | ||
] | ||
} |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.