0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.