I’m using the USelectMenu component from the Nuxt UI library, and I need to ensure that all the options that the user can select are displayed. I have that covered with my mapped_looking_for method, and the options are bound correctly. Then, I need to display all the options that the user has already selected, which I also have working to some extent.
The problem is that the select should work in such a way that if an option is selected, there should be a tick next to it on the right indicating that it is indeed selected. However, even though it shows that 5 options are selected, I don’t see the tick next to them. I am also unable to interact with them in such a way that I could remove options. Essentially, it doesn’t work for me; I would have to manually delete them from the database.
Could anyone offer some advice? I’m relatively new to working with APIs, and I might be passing the data incorrectly. Thank you.
This is frontend.
<USelectMenu v-model="looking_fors" :options="mapped_looking_for" multiple
:placeholder="getLookingForPlaceholder" />
<script>
const mapped_looking_for = ref([]);
const looking_for = ref([]);
const fetchLookingFor = async () => {
try {
const { data } = await api.get('/api/lookingFor');
mapped_looking_for.value = data.data.map(item => ({
label: item.name,
value: item.id
}));
console.log('Mapped looking_for:', mapped_looking_for.value);
} catch (error) {
console.error('Error fetching looking for options:', error);
}
};
const getLookingForPlaceholder = computed(() => {
const count = profile.value.looking_fors?.length || 0;
return count > 0 ? `${count} selected` : 'None';
});
const fetchProfile = async () => {
try {
const { data } = await api.get('/api/profiles/show');
profile.value = data.profile;
user.value = data.user;
looking_for.value = data.profile.looking_fors.map(item => item.id);
} catch (error) {
console.error('Error fetching profile:', error);
}
};
const updateProfile = async () => {
try {
const looking_for_ids = looking_for.value.map(item => item.value);
await api.put(`/api/profiles/${profile.value.id}/looking-for`, {
looking_for: looking_for_ids
});
console.log('Profile updated successfully');
} catch (error) {
console.error('Error updating profile:', error);
}
};
</script>
This is what I have on backend.
public function updateLookingFor(Request $request): JsonResponse
{
$user = $request->user();
$profile = $user->profile;
$validated = $request->validate([
'looking_for' => 'array',
'looking_for.*' => 'exists:looking_fors,id',
]);
$profile->lookingFors()->syncWithoutDetaching($validated['looking_for']);
return response()->json(['message' => 'Looking for updated successfully']);
}
// And route
Route::put('/profiles/{id}/looking-for', [ProfileController::class, 'updateLookingFor']);