Search code examples
javascriptreactjsuse-statereact-context

Using Context and hook in react js


is me againg... 3 hours ago I had a questions about how used context and usestate in react, but I found the answer myself, but now, I'm having anther trouble, is about setState or setcategoria in my case, so this are the component:

CategoriaState.js

const [ categorias, setCategorias ] = useState(Data);

const AddCategoria = (description, idPadre) => {
    categorias.push({
        id: categorias.length,
        description: description,
        idPadre: idPadre
    });
    console.log(categorias);
    return true;
};

const DelCategoria = (id) => {
    const newData = categorias.filter( item => item.id !== id );  
    setCategorias({ newData });
    return true;
};

return(         
    <CategoriaContext.Provider
                value={{ 
                        categorias: categorias,
                        GetCategorias,
                        AddCategoria,
                        DelCategoria
                }}                 
    >
        {props.children}
    </CategoriaContext.Provider> 
)

the functions GetCategorias, Addcategorias are working so good!!! but the problem is in DelCategoria, this is the error:

Uncaught TypeError: categorias.map is not a function

so if I commnet in line setCategorias({ newData }); in function DelCategoria, the error is not displayed, but fortunately the variable categoria is not updated, I think the error is there.

so I call de function DelCategoria from my component AllCat.js

    .
    .
    .
    const { categorias, GetCategorias, DelCategoria }  = useContext( CategoriaContext );

    useEffect(() => {
        GetCategorias();
    },[])
   .
   .
   .

   <button onClick={ () => DelCategoria(item.id) } >
      Del Item                                    
    </button> 

my intention is created an simple example in react js using context and usestate, I want understand this api(use context)

thanks!!


Solution

  • You are setting a categorias property as an object, not an array

       setCategorias({ newData });
    

    Just make a setCategorias(newData) instead and I think this should work