preactjs / signals

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

No updates with array data #368

Closed isolin closed 1 year ago

isolin commented 1 year ago

Hi! I started using preact and signals just recently. Maybe I am doing something wrong, but I thing I just followed the TODO List example in the docs. Please let me know if this is a bug or just my mistake. Note that I am using typescript.

This is my global state exported and shared all over the app.

const state = {
  //some other signals
  arr: signal([""])
}

export default state;

Then I have the control elements like

//state is the global state as defined above
export class Arr extends Component
{
    render() {
        return <div>
            Length: {state.arr.value.length}
            <button onClick={() => {
                state.arr.value.push("123");
                console.log(state.arr.value.length)} 
            }>Add new item</button>
        </div>;
    }
}

The Arr component initially displays Length: 1 but when I push a new value to the array the length does not get updated. The console output called in onClick correctly shows the increasing number of items as I keep pressing the button.

I work with Firefox, the preact packages are:

├── @preact/signals@1.1.3
├── preact-render-to-string@5.2.6
├── preact-router@3.2.1
├── preact@10.15.1
├── typescript@4.9.5
jaredcwhite commented 1 year ago

Arrays aren't internally reactive, so you would need to create a new array with the contents of the old array, along with a new element.

state.arr.value = [...state.arr.value, "123"]
isolin commented 1 year ago

Thank you very much for the explanation. I didn't notice the todos.value = [...todos.value, { text: text.value }]; in the example in the official docs.

Now it works fine for me!