skip to Main Content

I’m new to react and I have a question about optimising the code in the project.
It seems that the React.UseContext or useContext hook is suitable for my case, but I don’t fully understand the syntax/approach with this hook.

My project is slowly starting to grow and some function or variables have to be dragged across 3 or more components just to use it in one place:

App.js

const [costs, setCosts] = useState(null);
const deleteCostHandler = (itemId) => {
    setCosts((prevCosts) => {
      let res = prevCosts.filter((cost) => cost.id !== itemId);
      return [...res];
    });
  };
//jsx..
 <ConstContext.Provider><Cost value={{deleteCostHandler}} /></ConstContext.Provider>

Cost.js

const costDeleteHandler = (incomeId) => {
    props.dataDelete(incomeId);
};
 <CostList costDelete={costDeleteHandler} />

CostList.js

const passDataForUpdateHandler = (deletedId) => {
    props.costDelete(deletedId);
};
<CostItem refreshAfterDelete={passDataForUpdateHandler} />

And finaly..

CostItem.js

const onDeleteHandler = () => {
    fetch("http://localhost:8000/costs/" + props.id, {
      method: "DELETE",
    }).then(() => {
      props.refreshAfterDelete(props.id);
      props.clearInputs(true);
    });
  };
 <button type="button" onClick={onDeleteHandler}>

I tried to create ConstContext.js file and store the needed functionality to cut the code and use it like:
ctx.deleteCostHandler(props.id);, but i get error ‘deleteCostHandler is not a function’, so I’m clearly doing something wrong.
I would be grateful if someone could explain/direct me to the right solution.

2

Answers


  1. Chosen as BEST ANSWER

    Found error, wrong function name passed in Cost.js component.


  2. You are not providing the context anywhere in your app’s component tree. At someplace, usually somewhere above the components that need to consume the context, you add the Provider component exposed on the context object itself.

    Take a look at the React documentation on this.

    Edit: You are not consuming it anywhere either. Please provide an example of the code that produces the error you mentioned in the question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search