pomber / didact

A DIY guide to build your own React
https://pomb.us/build-your-own-react/
6.29k stars 531 forks source link

Use state hook not working on functional component #41

Closed lucas-almeida026 closed 2 years ago

lucas-almeida026 commented 2 years ago

Hi there, I was having problems implementing the Didactjs so at some point I decided to just copy the intire file and a got an error

Error: Uncaught TypeError: Cannot read properties of null (reading 'alternate')

Context:

function useState(initial) {
  const oldHook =
    wipFiber.alternate &&  // <- Error happened here
    wipFiber.alternate.hooks &&
    wipFiber.alternate.hooks[hookIndex]
  const hook = {
    state: oldHook ? oldHook.state : initial,
    queue: [],
  }
...
}

My main file:

import Didact from './lib.mjs'

function App(props = { title: 'title' }){
  const [ counter, setCounter ] = Didact.useState(0)
  return Didact.createElement(
    'div',
    null,
    Didact.createElement(
      'h1',
      null,
      `${props.title}: ${counter}`
    ),
    Didact.createElement(
      'div',
      null, 
      Didact.createElement(
        'button',
        { onClick: () => console.log('click') },
        '+'
      ),
      Didact.createElement(
        'button',
        null,
        '-'
      )
    )
  )
}

Didact.render(App({ title: 'some' }), document.getElementById('root'))

What I've tried:

I tried to make one more verification

From:

const oldHook = wipFiber.alternate && wipFiber.alternate.hooks ...

To:

const oldHook = wipFiber && wipFiber.alternate && wipFiber.alternate.hooks ...

But then i got another error:

Error: Uncaught TypeError: Cannot read properties of null (reading 'hooks')

Context:

function useState(initial) {
  ...
  wipFiber.hooks.push(hook) // <- Error happened here
  hookIndex++
  return [hook.state, setState]
}

Then I tried a bunch of another thing but got nowhere, so I hope find some answers here