Rev 3432 | AutorÃa | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { createContext, useCallback } from 'react';
import { useFetch } from '@hooks';
export const ValuesContext = createContext();
export default function ValuesProvider({ url, children }) {
const { data, isLoading: loading, mutate } = useFetch(url, { items: [] });
const { items: values, link_add, total } = data;
const addValue = useCallback(
(newValue) => {
const newValues = [...values, newValue];
mutate({ ...data, items: newValues });
},
[values, mutate]
);
const removeValue = useCallback(
(valueId) => {
const newValues = values.filter((value) => value.id !== valueId);
mutate({ ...data, items: newValues });
},
[values, mutate]
);
const updateValue = useCallback(
(updatedValue) => {
const newValues = values.map((value) =>
value.id === updatedValue.id ? updatedValue : value
);
mutate({ ...data, items: newValues });
},
[values, mutate]
);
const getValueById = useCallback(
(valueId) => values.find((value) => value.id === valueId),
[values]
);
return (
<ValuesContext.Provider
value={{
loading,
values,
addUrl: link_add,
total,
addValue,
removeValue,
updateValue,
getValueById
}}
>
{children}
</ValuesContext.Provider>
);
}