0

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,
    }
}
rhemmuuu
  • 1,147
  • 2
  • 5
  • 19

1 Answers1

0

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.

v-moe
  • 1,203
  • 1
  • 8
  • 25