React hooks context - how to update context with onclick event handler ? Getting Invalid hook call err when I try

Viewed 394

I am trying to update a context with a callback. When I execute the callback its fine, but when I try to update the property inside of it im getting the err Error: Invalid hook call. Im not very familiar with context and researched and cant figure it out. Any help would be great. Thank you.

const initialState = {
  language:"en",
  showSomething:false,
  setShowSomething:setShowSomething
}


const StateContext = createContext(initialState)

export const useGlContext = () => {
  const glContext = useContext(StateContext)
  return glContext
}

function setShowSomething(el) {
  const context = useGlContext()
  context.showSomething=el
}

function App() {
  const context = useContext(StateContext)
  const { language, showSomething, setShowSomething } = context
  return (
    <Child 
    language={language}
    showSomething={showSomething}
    setShowSomething={setShowSomething}
    />
  )
const Child = ({language, showSomething, setShowSomething }) => {
    return (
      <button onClick={() => setShowSomething(true)}></button>
    )
}
}

Edit:

I am wrapping the root component inside Provider:

    <StateContext.Provider value={initialState}>
       <App />
    </StateContext.Provider>
1 Answers

You should take into account that event argument is passed in onClick. Try:

onClick={event => setShowSomething(event,true)}

Consider using arrow functions:

const setShowSomething = (event, el) => {
  event.preventDefault(); <- must add for no infinite rerender
  const context = useGlContext()
  context.showSomething=el
}
Related