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
 
3
import { useFetch } from '@hooks';
4
 
5
export const GoalsContext = createContext();
6
 
7
export default function GoalsProvider({ url, children }) {
8
  const { data, isLoading: loading, mutate } = useFetch(url, { items: [] });
9
  const { items: goals, link_add, total } = data;
10
 
11
  const addGoal = useCallback(
12
    (newGoal) => {
13
      const newGoals = [newGoal, ...goals];
14
      mutate({ ...data, items: newGoals });
15
    },
16
    [goals, mutate]
17
  );
18
 
19
  const deleteGoal = useCallback(
20
    (goalId) => {
21
      const newGoals = goals.filter((goal) => goal.id !== goalId);
22
      mutate({ ...data, items: newGoals });
23
    },
24
    [goals, mutate]
25
  );
26
 
27
  const updateGoal = useCallback(
28
    (updatedGoal) => {
29
      const newGoals = goals.map((goal) => (goal.id === updatedGoal.id ? updatedGoal : goal));
30
      mutate({ ...data, items: newGoals });
31
    },
32
    [goals, mutate]
33
  );
34
 
35
  const getGoalById = useCallback((goalId) => goals.find((goal) => goal.id === goalId), [goals]);
36
 
37
  return (
38
    <GoalsContext.Provider
39
      value={{
40
        loading,
41
        goals,
42
        addUrl: link_add,
43
        total,
44
        addGoal,
45
        deleteGoal,
46
        updateGoal,
47
        getGoalById
48
      }}
49
    >
50
      {children}
51
    </GoalsContext.Provider>
52
  );
53
}