'React context isn't available from function inside component

Hello I have a problem with React Context. I'm using React-DnD and I'm trying to get context in feed function but it's empty. In this function I'm getting context default value but outside that function I'm getting correct values and I don't know why.

const Dog = () => {
const needsCtx = useContext(NeedsContext);
const invCtx = useContext(InventoryContext);
console.log(invCtx);
const feed = () => {
    console.log(invCtx);

};
needsCtx.saveCurrentContextToDatabase();
const [{ isOver }, drop] = useDrop(
    () => ({
        accept: "food",
        drop: () => feed(),
        collect: (monitor) => ({
            isOver: !!monitor.isOver(),
        }),
    }),
    []
);
return (
    <div className={styles["wrapper-dog"]}>
        <img ref={drop} className={styles.dog} alt="dog" src={dog}></img>
    </div>
);
};

context:

 import React, { useState } from "react";
export const InventoryContext = React.createContext({
    items: {},
    setItems: () => {},
});

const InventoryContextProvider = (props) => {
    const [items, setItems] = useState({});
    return (
        <InventoryContext.Provider value={{ items: items, setItems: setItems }}>
            {props.children}
        </InventoryContext.Provider>
    );
};
export default InventoryContextProvider;


Solution 1:[1]

I'm going to make suggestions here, and continue to edit this answer.

<InventoryContext.Provider value={{ items: items, setItems: setItems }}>

This line confuses me most. Mostly because, you're using state inside of the Provider, so why do you also need to declare items and setItems inside the context itself?

Since you're using the state inside the Provider, couldn't you remove the items and setItems inside the context itself, and then just pass as:

<InvetoryContext.Provider value={{ items, setItems }}>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nimantha