Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 }}>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!