React Context - Consume Field Not Working

Viewed 34

I'm trying to consume some values from a context so that when the props are passed over onto the page and then mapped, it can either hide it or show it. I can't get it to work properly

import react, { useContext } from 'react';

// MUI Icons
import DashboardRoundedIcon from '@mui/icons-material/DashboardRounded';
import AddCircleOutlineOutlinedIcon from '@mui/icons-material/AddCircleOutlineOutlined';

import { Button } from '@mui/material';
import MaterialTable from '../../components/table';
import Chart from '../../components/chart/index';

import { priceVarianceChart, priceVarianceLineChart } from './chartData';

import { AuthenticationContext } from '../../store/AuthStore';

const { homeKPI1 } = useContext(AuthenticationContext);

export const priceVariance = {
  props: {
    locked: {homeKPI1},

These props are passed onto a page which uses a component to render different KPI cards. homeKPI1, homeKPI2 etc are boolean fields from an external database

1 Answers

What is wrong in your code:

  1. You must not use hooks outside of a component or another hook. useContext is hook.

  2. Also, to use useContext, you must have a context provider in the component's parent.

Please, check out the documentation.

An example of Context API usage:

import React from 'react';

export const UserContext = React.createContext();

export default function App() {
  return (
    <UserContext.Provider value="Reed">
      <User />
    </UserContext.Provider>
  )
}

function User() {
  const value = React.useContext(UserContext);  
    
  return <h1>{value}</h1>;
}
Related