I want to use useContext() inside componentDidMount() function because I need Id Partition inside it but it gave me error :
React Hook "useAppContext" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function ?
class Invhom extends Component {
//...
componentDidMount(){
const {IdPartition,setIdPartition } = useAppContext(); // ... Error
let value = this.IdPartition;
// console.log(value);
axios.get('http://localhost:9091/inventaire/select_inventaire');
} }
//...
}
//------------------------------context.js----------------------------------------
export const AppContext = createContext(null);
export function useAppContext() {
return useContext(AppContext);
}
CodePudding user response:
Please see https://reactjs.org/docs/hooks-rules.html :
Only Call Hooks from React Functions
You can't call Hooks from class components.
As noted in the FAQ, you do not have to rewrite your class components. However, please consider using function components and Hooks for new code.