skip to Main Content

I’m tried to access only few values in my component but have to define all the values in useContext. if a am not defining the sequence its giving error

const [handleChange, isEditMode, setIsEditMode, partnerData, setPartnerData] = useContext(FilterContext);

here i want to use only two elements isEditmode and PartnerData

3

Answers


  1. Create the context as an object and use curly braces to get just one property of it.

    const FilterContext = createContext({
      handleChange: function (...) {...},
      isEditMode: false,
      setIsEditMode: function (...) {...},
      partnerData: function (...) {...},
      setPartnerData: function (...) {...}
    })
    
    const { isEditmode, partnerData } = useContext(FilterContext)
    
    Login or Signup to reply.
  2.   const [handleChange, isEditMode, setIsEditMode, partnerData, setPartnerData] = useContext(FilterContext);
    

    You can use destructuring assignment

    const [, isEditMode, ,partnerData] = useContext(FilterContext);
    
    Login or Signup to reply.
  3. In order to access only two values from the FilterContext using useContext, you can destructure the values directly in the useContext function.

    const { isEditMode, partnerData } = useContext(FilterContext);
    

    You have to make sure that the FilterContext is properly defined and accessible within the component hierarchy.

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