I'm coding a Vue app for my first project ever. I'm using json-server as simulating server waiting to learn how Firebase works later. At some point I get to fetch some data and find an object by id property through the array of data I fetched to get another proprety from it. The problem is that the object stays undefined, can't understand how. I'm using the composition API:
export default {
props: ['id'],
setup(props) {
const caregivers = ref([]);
const caregiverById = ref(null);
const error = ref('');
onMounted(async () => {
try {
const response = await fetch('http://localhost:3000/caregivers');
if (!response.ok) {
throw new Error('No available data');
}
const data = await response.json();
caregivers.value = data;
console.log(caregivers.value);
// Find the caregiver by ID
caregiverById.value = caregivers.value.find((caregiver) => caregiver.id === props.id);
console.log('caregiverById:');
console.log(caregiverById.value);
} catch (err) {
error.value = err.message;
console.log(error.value);
}
});
return { caregivers, caregiverById, error };
}
}
The console.log returns caregiverById.value still undefined while caregivers.value is defined and returns an array as expected while the props seems to be fine too and well passed:
Funny enough I tried to rewrite everything with no composition API with a simple .fetch() method and... it works, logging the right object, so I'm sure that and object with that id passed as props always exists in the caregivers.
Written like this everything works fine:
export default {
props: [ 'id' ],
components: { EvaluationCard },
data() {
return {
caregivers: [],
caregiverById: [],
error: '',
}
},
mounted() {
fetch('http://localhost:3000/caregivers')
.then((res) => res.json())
.then((data) => this.caregivers = data)
.then(() => console.log(this.caregivers))
.then(() => this.caregiverById = this.caregivers.find((caregiver) => caregiver.id = this.id))
.then(() => console.log(this.caregiverById))
.catch(err => console.log(err.message))
}
}
Why it doesn't work with the composition API? I'm missing something?