I’m having trouble mapping a useState. I have a context that sends a simple useState to my useFilter hook (const[ valueSelects, setValueSelects] = useState({})).
In the hook I have a function called getInitFilters that tries to initialize the valueSelects of a filter. This function maps a constant called initFilter from the outside and with that data I try to put it inside the useState of valueSelects.
The final result of [id], [key] and value is fine, it maps the two values of the array, it goes through them but when it reaches the useState , the result is only one of them, the category is not there
Object { tailles: {…} }
tailles: Object { M: 1 }
I want the value selects to be equal to the initFilter constant
use of the hook
const initFilter = { 'categorie': { 'TOUS': 'all' }, 'tailles': { 'M': 1 } }
const { filterProducts } = useFilter(initFilter);
const filteredProducts = filterProducts(products[0]
El valueSelets en el contexto es solo un useState,
const [valueSelects, setValueSelects] = useState({})
import { useEffect } from "react";
import { useUi } from "../context/useUi";
export const useFilter = (ids) => {
const { valueSelects, setValueSelects, range } = useUi();
useEffect(() => {
getInitFilters(ids);
}, [])
const getInitFilters = () => {
Object.keys(ids).map(id => {
const key = Object.keys(ids[id])[0];
const value = Object.values(ids[id])[0]
setValueSelects({ ...valueSelects, [id]: { [key]: value } })
});
}
const filterProducts = (datas) => {
return datas.filter(data => {
return (Math.round(data.price * optionValue) >= range &&
(valueFilter === 'all' || data.type === valueFilter))
})
}
return { filterProducts }
}