0

I am using Context-Api and am trying to use a function provided from my file in a lifecycle method. the function isnt wrapped in a consumer of course so i looked at the documentation and set value to context. this still isnt working.Everyting is working in my return of my class component but component did mount does not work.

import { ProductConsumer } from '../context';

export default class Details1 extends Component
componentDidMount() {
    let value = this.context;
    let id = this.props.match.params.id;
    value.handleDetail(id);
  }

render() {
{value => {
          const {
            id,...} = value.detailProduct;
    return (
      <ProductConsumer>
        {value => {
My Component
 </ProductConsumer>

 export const Details = () => (
  <Product.Consumer>
    {context =>
      <Details1 context={context}/>

    }
  </Product.Consumer>
)

1 Answers1

1

You can either wrap the component with the consumer, passing it the function as a prop, or (better - ) convert your component to a functional component, using the useContext hook to get the values from your context.

import React, { useContext } from "react"; 
import someContext from "./context-path";

const MyComponent = () => {
  const { myFunction } = useContext(someContext);
  ...
};
Gilad Bar
  • 1,302
  • 8
  • 17
  • How can i wrap a lifecycle method in a consumer? – TheGreen Lightbulb Jul 15 '19 at 20:33
  • Not the lifecycle method, but the class component itself – Gilad Bar Jul 15 '19 at 20:35
  • It is wrapped in a product consumer but this.props.context returns null in my Component Did mount but works in my components elements. Let met update this with the full component – TheGreen Lightbulb Jul 15 '19 at 20:37
  • It's not enough to just wrap with a consumer, the consumer should receive a function as its children. The function receives the values given by the provider and returns whatever you want to render. {value => /* render something based on the context value */} – Gilad Bar Jul 15 '19 at 20:39