Problems using React Context

Asked

Viewed 268 times

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?

  • 1

    I got it, thanks

  • Only one question: if I wanted ComponentTwo had access to the variables of NameChoose, but it wouldn’t render on it, it would have some hook that I could use ?

  • 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.

  • 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!

  • 1

    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 the ComponentTwo , 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,!!

  • Put it all in Contextapi that part of the user settings and use it in the components! That’s how you do it!

Show 2 more comments

1 answer

0


Your code is totally wrong, because when you create a React.Context means that you want several components to share the same state, functions, etc. To make this work, you create a Context and a Provider that involves all components that need to use the same code, minimum example:

const CounterContext = React.createContext();
const CounterProvider = ({children}) => {
  const [counter, setCounter] = 
    React.useState(0);
  return (
    <CounterContext.Provider value={{counter, setCounter}}>
      {children}
    </CounterContext.Provider>
  )
}


const View1 = () => {
  const context = React.useContext(CounterContext);
  return (
    <div>{context.counter}</div>
  )
}

const View2 = () => {
  const context = React.useContext(CounterContext);
  const handleIncrement = () 
    => context.setCounter(state => state + 1);
  const handleDecrement = () 
    => context.setCounter(state => state - 1);
  return (
    <div>
      <button onClick={handleIncrement}>Incrementar</button>
      <button onClick={handleDecrement}>Decrementar</button>
    </div>
  )
}
const View3 = () => {
  const context = React.useContext(CounterContext);
  return (
    <div>{context.counter}</div>
  )
}
const Root = () => {
  return (
    <CounterProvider>
      <View1 />
      <View2 />
      <View3 />
    </CounterProvider>
  )
}

ReactDOM.render( <Root/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

A simple counter code and a function to change the value of that counter, 3 components View who share the same state because they are involved in Provider servant.

References:

Note: besides your setup is wrong, your code is very poorly organized, these are important factors even if you are a beginner, so pay attention not to create a form code for example directly within the Provider, is unusual and in your code caused many problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.