Home » vue » Vue update array state using the composition api

Vue update array state using the composition api

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to create some kind of state using the composition api in vue 3 with the following file:

// useNotifications.ts
const state = reactive<Array<Notification>>([]);

export function useNotifications() {
  return {
    state,
    add: (notification: Notification) => {
      state.push(notification);
    },
  };
}

This notification state is read and rendered in html from this the below:

// TheNotifications.vue
setup() {
    const notifications = useNotifications();

    let first = notifications.state[0];

    return {
      first,
    };
  },

And notifications are added at some form submit event like so:

// SomeForm.vue
notifications.add({ type: "success", text: "Food added" });

However, TheNotifications never sees the changes when pushing. I tried some different methods, for example with toRef, but I had no success. I’m new to this composition api thing and I was wondering what I’m missing.

Answers:

reactive doesn’t work with Arrays. Seems to be a limitation of the composition api. You can read a similar discussion here.

Use ref instead of reactive, it should work fine. I have built a few apps like this and can confirm it working.
So write: const state = ref<Array<Notification>>([]);, you will have it working. And as a rule of thumb, use ref for anything but objects, that’s when you want to use reactive. It’s more complex than that but if you use them like this, it will always work.