'Laravel + Vue 3: Add item to each element of array from Composable

I'm trying to add toShow to each element of hello array but looping is not working.

The response from api/test (calls TestController) is assigned to hello.

Test.vue

<script>
import useTest from "../composables/test.js"
import { onMounted } from 'vue'

export default {
    setup() {
        const { hello, getHello } = useTest()

        onMounted(getHello)

        // trying to print the first element of hello to the console, output: undefined
        console.log(hello[0])

        // it's supposed to be an array but looping is not working
        hello.forEach(element => {
            console.log(element)

            // trying to add new item here
            element.toShow = false
        });

        return {
            hello,
        }
    },
}
</script>

TestController:

public function index()
{
    $hello = array(['id' => 13, 'name' => 'world'], ['id' => 14, 'name' => 'world!']);
    return $hello;
}

composable: test.js

import { ref } from 'vue'
import axios from 'axios'

export default function useTest() {
    const hello = ref([]) // add ref to it coz otherwise I can't assign value coz it says it's read-only

    // set value for hello from api
    const getHello = async () => {
        let response = await axios.get("/api/test")
        hello.value = response.data.hello
    }

    return {
        hello,
        getHello,
    }
}


Solution 1:[1]

You have to unwrap the ref inside <script>:

hello.value.forEach(element => { // whatever

You should also await getHello() in the onMounted hook and iterate there, not outside of onMounted.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 v-moe