so am trying to get some data in a form of a state in react.js and i need to use it in the useContext so i can perform an Api call so please if someone can help that would be a please <3 and really helpful and thank you
If I understand your question correctly, you can do:
// MyComponent.js
import React, { useState, createContext } from "react";
// Note that you have to export the context to use it elsewhere
export const MyContext = createContext(null);
const MyComponent = () => {
const [myState, setMyState] = useState();
// Provider provides the context to components that are nested under it
return (
<MyContext.Provider value={{ myState: myState, setMyState: setMyState }}>
<MyChildrenComponents />
</MyContext.Provider>
);
};
value is accessible in any component that's nested under the provider. In this case, the provider is <MyContext.Provider>. And value is accessible in <MyChildrenComponents />.
--
To extract value, we use useContext as such:
// MyChildrenComponents.js
import React, { useContext } from 'react';
import { MyContext } from './MyComponent.js';
const MyChildrenComponents = () => {
const { myState, setMyState } = useContext(MyContext);
// ...
}
You can read more about React context here (the docs).