# Fetch Wrapper

A fetch wrapper is a piece of code that wraps the JavaScript `fetch()` function, which is used to make HTTP requests. It typically provides a simpler, more convenient interface for making common types of requests, such as GET, PUT, POST, and DELETE.

Here is an example of a fetch wrapper that provides these four methods:

```javascript
class FetchWrapper {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }

  async get(url) {
    const response = await fetch(`${this.baseUrl}${url}`);
    return response.json();
  }

  async put(url, data) {
    const response = await fetch(`${this.baseUrl}${url}`, {
      method: 'PUT',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return response.json();
  }

  async post(url, data) {
    const response = await fetch(`${this.baseUrl}${url}`, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return response.json();
  }

  async delete(url) {
    const response = await fetch(`${this.baseUrl}${url}`, {
      method: 'DELETE',
    });
    return response.json();
  }
}

const fetchWrapper = new FetchWrapper('https://my-api.com');

// GET request
fetchWrapper
  .get('/users')
  .then((users) => console.log(users))
  .catch((error) => console.error(error));

// PUT request
fetchWrapper
  .put('/users/1', { name: 'John', age: 30 })
  .then((user) => console.log(user))
  .catch((error) => console.error(error));

// POST request
fetchWrapper
  .post('/users', { name: 'Jane', age: 25 })
  .then((user) => console.log(user))
  .catch((error) => console.error(error));

// DELETE request
fetchWrapper
  .delete('/users/1')
  .then((user) => console.log(user))
  .catch((error) => console.error(error));
```

In this example, the `FetchWrapper` class has a constructor that takes a base URL as an argument. It then provides four methods for making GET, PUT, POST, and DELETE requests using the `fetch()` function. Each method returns a Promise that resolves with the JSON response from the server.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://demirels-organization.gitbook.io/javascript-tutorial/fetch-wrapper.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
