Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3209 | Rev 3416 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3209 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) => {
3373 stevensc 13
      const newGoals = [newGoal, ...goals]
3209 stevensc 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) =>
30
        goal.id === updatedGoal.id ? updatedGoal : goal
31
      )
32
      mutate({ ...data, items: newGoals })
33
    },
34
    [goals, mutate]
35
  )
36
 
37
  const getGoalById = useCallback(
38
    (goalId) => goals.find((goal) => goal.id === goalId),
39
    [goals]
40
  )
41
 
42
  return (
43
    <GoalsContext.Provider
44
      value={{
45
        loading,
46
        goals,
47
        addUrl: link_add,
48
        total,
49
        addGoal,
50
        deleteGoal,
51
        updateGoal,
52
        getGoalById
53
      }}
54
    >
55
      {children}
56
    </GoalsContext.Provider>
57
  )
58
}