This is a follow-on question from my previous question here: Accessing ref values from composable
Here is my App code:
<template>
{{ reversed_names }}
</template>
<script>
import { ref, watchEffect } from "@vue/runtime-core";
import getData from "./composables/getData";
import reverseNames from "./composables/reverseNames";
export default {
name: "App",
setup() {
var filenames = ["test1.json", "test2.json"];
const { names_data, error, load_data } = getData(filenames);
load_data();
const reversed_names = ref({});
watchEffect(() => {
const reversed_names = reverseNames(names_data.value);
console.log("revnames inside watchEffect", reversed_names.value);
});
console.log("revnames outside watchEffect", reversed_names);
return { names_data, reversed_names };
},
};
</script>
and here is the reverseNames
function:
import { ref } from "@vue/runtime-core";
const reverseNames = (names_data) => {
const reverse_names = ref({})
var filenames = Object.keys(names_data)
for (let f in filenames) {
var filename = filenames[f]
reverse_names.value[filename] = {}
var members = names_data[filename]["members"]
for (let n in members) {
let name = members[n];
var reverseName = name.split("").reverse().join("");
reverse_names.value[filename][name] = reverseName
}
}
return reverse_names
};
export default reverseNames
The watchEffect
is there so I can use names_data
once the data is loaded from a file (see linked question above).
The code works fine up to the call to reverseNames
.
names_data.value
contains the following:
{ "test1.json":
{ "members":
{ "0": "Alice",
"1": "Bob",
"2": "Charlie"
}
},
"test2.json":
{ "members":
{ "0": "David",
"1": "Elizabeth",
"2": "Fred"
}
}
}
Here's the confusing part:
Inside the watchEffect
function, the console shows the correct return dictionary from the function.
However, outside the watchEffect
function, the console just shows the empty ref({})
defined before the watchEffect()
call.
It is the empty dictionary that is returned by setup()
and displayed in the template.
How can I get the setup()
to return the reversed_names
from inside the watchEffect
?