Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3432 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3719 stevensc 1
import React, { createContext, useCallback } from 'react';
2
import { useFetch } from '@hooks';
3
 
4
export const ValuesContext = createContext();
5
 
6
export default function ValuesProvider({ url, children }) {
7
  const { data, isLoading: loading, mutate } = useFetch(url, { items: [] });
8
  const { items: values, link_add, total } = data;
9
 
10
  const addValue = useCallback(
11
    (newValue) => {
12
      const newValues = [...values, newValue];
13
      mutate({ ...data, items: newValues });
14
    },
15
    [values, mutate]
16
  );
17
 
18
  const removeValue = useCallback(
19
    (valueId) => {
20
      const newValues = values.filter((value) => value.id !== valueId);
21
      mutate({ ...data, items: newValues });
22
    },
23
    [values, mutate]
24
  );
25
 
26
  const updateValue = useCallback(
27
    (updatedValue) => {
28
      const newValues = values.map((value) =>
29
        value.id === updatedValue.id ? updatedValue : value
30
      );
31
      mutate({ ...data, items: newValues });
32
    },
33
    [values, mutate]
34
  );
35
 
36
  const getValueById = useCallback(
37
    (valueId) => values.find((value) => value.id === valueId),
38
    [values]
39
  );
40
 
41
  return (
42
    <ValuesContext.Provider
43
      value={{
44
        loading,
45
        values,
46
        addUrl: link_add,
47
        total,
48
        addValue,
49
        removeValue,
50
        updateValue,
51
        getValueById
52
      }}
53
    >
54
      {children}
55
    </ValuesContext.Provider>
56
  );
57
}