0
I’ve been studying React and developing an app, but I have a problem when I try to use context
. In one component, I create the context and provide its value, but when I try to use the current value of the context in another component, I have the default value. Code:
export const OwnerInformationContext = React.createContext({})
function NameChoose() {
...
const [ownerInformation,setOwnerInformation] = useState({})
function onpressSubmitButton(e : FormEvent) {
e.preventDefault();
...
setOwnerInformation({name:'name',roomId:'id',owner:'true'})
}
return(
<div className="page-container">
<OwnerInformationContext.Provider value={ownerInformation} />
...
<form onSubmit={onpressSubmitButton}>
...
</form>
...
);
}
export default NameChoose;
-> In the component above, I define it and in the below I try to use it:
import { OwnerInformationContext } from '../NameChoose/index'
function ComponentTwo(){
const consumeOwnerContext = useContext(OwnerInformationContext)
useEffect(() => {
console.log(consumeOwnerContext)
}, [])
return <h1>test</h1>
}
However, I can only access the default value, which is {}
understood the example?
– novic
I got it, thanks
– uKn_70
Only one question: if I wanted
ComponentTwo
had access to the variables ofNameChoose
, but it wouldn’t render on it, it would have some hook that I could use ?– uKn_70
There is no way, if the state is local it is only of the component itself! if the state is for everyone it has to be Redux or Context Api.
– novic
And there is also not much logic that you reported! if you are starting maybe you need to understand more the logic of the process, what do you want to do? maybe there are better ways, almost sure there are!
– novic
It’s kind of like, this Component
NameChoose
is for choice of user name and other settings, ai wanted to take these settings and move to theComponentTwo
, however, I already do it by the backend with socket or with sessionStorage, but I wonder if there was any way to do by Hooks, but apparently there is,!!– uKn_70
Put it all in Contextapi that part of the user settings and use it in the components! That’s how you do it!
– novic