Rev 3416 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { createContext, useCallback } from 'react'
import { useFetch } from '@hooks'
export const GoalsContext = createContext()
export default function GoalsProvider({ url, children }) {
const { data, isLoading: loading, mutate } = useFetch(url, { items: [] })
const { items: goals, link_add, total } = data
const addGoal = useCallback(
(newGoal) => {
const newGoals = [newGoal, ...goals]
mutate({ ...data, items: newGoals })
},
[goals, mutate]
)
const deleteGoal = useCallback(
(goalId) => {
const newGoals = goals.filter((goal) => goal.id !== goalId)
mutate({ ...data, items: newGoals })
},
[goals, mutate]
)
const updateGoal = useCallback(
(updatedGoal) => {
const newGoals = goals.map((goal) =>
goal.id === updatedGoal.id ? updatedGoal : goal
)
mutate({ ...data, items: newGoals })
},
[goals, mutate]
)
const getGoalById = useCallback(
(goalId) => goals.find((goal) => goal.id === goalId),
[goals]
)
return (
<GoalsContext.Provider
value={{
loading,
goals,
addUrl: link_add,
total,
addGoal,
deleteGoal,
updateGoal,
getGoalById
}}
>
{children}
</GoalsContext.Provider>
)
}