Skip to content
This repository has been archived by the owner on Jul 19, 2020. It is now read-only.

Added explanation of the fetch module. #57

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions src/concepts/services/fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Fetch
## Introduction
The format module can be used to make requests to a server. This allows a Yew application to connect to a backend.
jstarry marked this conversation as resolved.
Show resolved Hide resolved

## Making requests
### Building requests
Before you can send a request to the server, you need to construct it. This should be done using the `yew::services::fetch::Request` object.
```rust
use yew::services::fetch::Request;
use yew::format::Nothing;
let get_request = Request::get("https://example.com/api/v1/something").body(Nothing).expect("Could not build that request")
```

```rust
use yew::services::fetch::Request;
use yew::format::Json;
use serde_json::json;
let post_request = Request::post("https://example.com/api/v1/post/something").header("Content-Type", "application/json").body(Json(&json!({"key": "value"}))).expect("Could not build that request.")
```
### Dispatching requests
To dispatch requests an instance of the `fetch_service` is needed. This can be created using `yew::services::FetchService::new()`. After building a request, it can be dispatched using `FetchService`'s `fetch` method. This method takes two arguments: a request and a `ComponentLink` callback with a closure taking an instance of `yew::services::fetch::Response`. This closure is run after the request finishes and can be used to initiatiate a redraw of the component by returning a message.

jstarry marked this conversation as resolved.
Show resolved Hide resolved
## Further reading
jstarry marked this conversation as resolved.
Show resolved Hide resolved
* [The API documentation](https://docs.rs/yew/0.14.3/yew/services/fetch/index.html)