preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.64k stars 89 forks source link

@preact/signals-core is not updating the value in the DOM, Nextjs 13 Page Router. #423

Closed malinjr07 closed 9 months ago

malinjr07 commented 9 months ago

Description

I'm Exploring @preact/signals-core with the Nextjs 13 (page router). I've initialized the state:


import { signal } from '@preact/signals-core';

export default function Home() {
  const welcomeText = signal(0);
  return (
    <main
      className={`flex min-h-screen flex-col gap-4 items-center justify-center p-24`}
    >
      <div className='flex flex-row gap-6 justify-center items-center px-6 py-10 bg-slate-50 '>
        <h4 className='text-base'>Signal Value</h4>
        <h6 className='text-xl font-semibold '>{welcomeText.value}</h6>
      </div>
      <div className='flex flex-row justify-center items-center gap-4 w-2/4 '>
        <button
          className='px-6 py-3 bg-yellow-500 '
          type='button'
          onClick={() => {
            welcomeText.value--;
            console.log('index.tsx:22 ~ Home ~ value:', welcomeText.value);
          }}
        >
          Decrement
        </button>
        <button
          className='px-6 py-3 bg-green-500 '
          type='button'
          onClick={() => {
            welcomeText.value++;
            console.log('index.tsx:32 ~ Home ~ value:', welcomeText.value);
          }}
        >
          Increment
        </button>
      </div>
    </main>
  );
}

Now, in the console log, the Signal is updating:

The Result screenshot:

signals-issue

File Directory:

codebase

Expected behavior

Rerender should happen on the value area, and the value should update on the DOM (Marked in Red).

Actual behavior

The value is not updating in the dom on click.

malinjr07 commented 9 months ago

I found the Solution. First, @preact/signals-react works just fine with the Next.js 13, page Router.

Steps to Verify:

  1. Install Nextjs App : npx create-next-app@latest
  2. Install @preact/signals-react: npm i @preact/signals-react or yarn add @preact/signals-react
  3. Most Important Do not use the useSignal hook outside of a component. If you want to declare signal outside of a component, use signal function instead:
    
    import { signal } from '@preact/signals-react';

export const welcomeText = signal('Awesome!');


4. **Must Do** Reload the website after implementation;