Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to use the useContext from preact. It seems I am doing something wrong, because my Context give undefined values.

Here is the main file:

const {render, h, createContext} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import SampleComp from './sample-comp.js'

export const ContextOne = createContext()
export const ContextTwo = createContext()

const RootComp = (props) => {
  return html`
  <ContextOne.Provider value=${'ContextOne'}>
    <ContextTwo.Provider value=${'ContextTwo'}>
      <${SampleComp}/>
    </ContextTwo.Provider>
  </ContextOne.Provider>
  `
}

render(html`<${RootComp} />`, document.body);

and here is the sample component:

const {useContext} = window.preactHooks
const {h} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import {ContextOne, ContextTwo} from './index.js'


export default function SampleComp (props) {
  const one = useContext(ContextOne)
  const two = useContext(ContextTwo)
  return html`<div>${one} - ${two}</div>`
}

What am I doing wrong here? I have been trying to figure it out for a few hours now but no idea.

question from:https://stackoverflow.com/questions/65540875/what-am-i-doing-wrong-with-usecontext

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

I got it.

Just after posting the question I realized that by using htm I need to wrap the providers in the template string to be a variable. so correct would be:

const RootComp = (props) => {
  return html`
  <${ContextOne.Provider} value=${'ContextOne'}>
    <${ContextTwo.Provider} value=${'ContextTwo'}>
      <${SampleComp}/>
    </ContextTwo.Provider>
  </ContextOne.Provider>
  `
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...