summaryrefslogtreecommitdiff
path: root/src/clients/actions.ts
blob: bfddf54980a6fca072d9ed37a2b75465d1a124b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { redirect } from "react-router-dom";
import { ApiClient } from "./api_client";
import { clearSessionStorage, deleteEmptyFields, setFormErrorsInSessionStorage } from "../lib/form_utils";
import Token from "../lib/token";

export async function editAccount({ request }) {
  const client = new ApiClient();
  let form_data = await request.formData();
  form_data = deleteEmptyFields(form_data);
  const response = await client.put("/account", form_data);

  if(response.status == 401)
    return redirect("/products");

  client.token.set(response.data.token);
  client.token.setRefresh(response.data.refresh);

  return redirect("/account");
}

export async function editAddress({ params, request }) {
  clearSessionStorage();
  const client = new ApiClient();
  let form_data = await request.formData();
  form_data = deleteEmptyFields(form_data);

  try {

    const response = await client.put(`/account/addresses/${params.addressId}`, form_data);

    if(response.status == 401 || response.status == 404)
      return redirect("/products");

    return redirect("/account");
  } catch(error) {
    if(error.response.status == 401) {
      new Token().logout;

      return redirect("/products")
    } 
    else {
      setFormErrorsInSessionStorage(error.response.data.errors);

      return redirect(`/account/addresses/${params.addressId}/edit`);
    }
  }
}