How can I create a reusable form component for each resource I create and/or update (Vue 3, vue-router, Pinia) - javascript

I have a Vue 3 app using Pinia stores that CRUD's data from my rest API. I've just started working with Vue 3 (from smaller vue 2 projects) and this is my first time using Pinia, so I'm still learning the intricacies of both.
One resource I manage from my api is called Applications, and I have a composable that manages API calls to retrive all apps, 1 app, or update the selected app. Instead of creating a form component to UPDATE, and a form component to CREATE applications, I'd like to create a single form component that handles both. So far I can populate my form with an existing application using a route that contains an application_id, and I create a new application if no application_id is in my route.params. I'm just not sure how to tell the form "Hey lets update this application instead of creating it.". I thought of using v-if directives that each create a <button> (one to run update, one to run create method) depending on there is an application_id in my route.params, but that seems inefficient (it may be correct, I'm just lacking knowledge). Here's my code:
// ApplicationStore.js (pinia store)
import { defineStore } from "pinia";
// Composable for axios API calls
import { getApplications, getApplicationByID, createApplication } from "#/composables/applications";
export const useApplicationStore = defineStore("application", {
state: () => ({
applications: [], //list of applications from database
application: {}, //currently selected application for edit form
loading: false,
success: "Successfully Created",
error: "",
}),
getters: {},
actions: {
async fetchApplications() {
this.loading = true;
this.applications = [];
const { applications, error } = await getApplications();
this.applications = applications;
this.error = error;
this.loading = false;
},
async fetchApplicationByID(id) {
this.loading = true;
const { application, error } = await getApplicationByID(id);
this.application = application;
this.error = error;
this.loading = false;
},
async createNewApplication() {
this.loading = true;
const { application, results, error } = await createApplication(this.application);
this.application = application;
this.error = error;
this.loading = false;
if (results.status === 201) {
// show this.success toast message
}
}
}
});
Here is my ApplicationForm component. It currently looks for route.param.id to see if an application is selected, if so it populates the form:
// ApplicationForm.vue
<template>
<section class="columns">
<div class="column">
<div v-if="error" class="notification is-danger">{{ error }}</div>
<div class="field">
<label class="label">Name</label>
<input v-model="application.name" class="input" type="text" />
</div>
<div class="field">
<label class="label">Location</label>
<input v-model="application.location" class="input" type="text" />
</div>
<div class="control">
<button #click="createNewApplication" class="button">Save</button>
</div>
</div>
</section>
</template>
<script setup>
import { useRoute } from "vue-router";
import { useApplicationStore } from "#/stores/ApplicationStore";
import { storeToRefs } from "pinia";
const route = useRoute();
const { applications, application, error } = storeToRefs(useApplicationStore());
const { createNewApplication } = useApplicationStore();
//checking if there's an id parameter, if so it finds the application from the list in the store
if (route.params.id) {
application.value = applications.value.find(app => app.id === Number(route.params.id));
} else {
//form is blank
application.value = {};
error.value = "";
}
</script>
Is there a preferred way to use this single form for both create and updates? I wonder if slots would be a good use case for this? But then I think I'd still end up making multiple form components for each CRUD operation. Also, I considered using a v-if to render the buttons based on if an application is in the store or not, like this:
<button v-if="route.params.id" #click="updateApplication" class="button">Update</button>
<button v-else #click="createNewApplication" class="button">Save</button>
I can't help but feel there is a better way to handle this (it is something I'll utilize a lot in this and future projects). This is my first big vue/pinia app. I'm loving the stack so far but these little things make me question whether or not I'm doing this efficiently.

If the form's UI is mainly expected to stay the same except for a few small differences (e.g. the button text), you could make the form emit a custom "submit" event and then handle that event from the parent component where you render the form (i.e. on the update page you have <ApplicationForm #submit="updateApplication"> and on the create page you have <ApplicationForm #submit="createNewApplication" />:
// ApplicationForm.vue
<template>
<section class="columns">
<div class="column">
<div v-if="error" class="notification is-danger">{{ error }}</div>
<div class="field">
<label class="label">Name</label>
<input v-model="application.name" class="input" type="text" />
</div>
<div class="field">
<label class="label">Location</label>
<input v-model="application.location" class="input" type="text" />
</div>
<div class="control">
<button #click="$emit('submit')" class="button">{{ buttonText }}</button>
</div>
</div>
</section>
</template>
As for the text, you can pass that as a prop (e.g. buttonText) to the ApplicationForm component. If some sections of the form are more substantially different than just different text between the "Update" and "Create" form, that's when you'd use slots.
I wouldn't recommend making the <ApplicationForm /> component responsible for reading the route parameters; that should generally be done only by the Vue component responsible for rendering the page (and then it should pass that data through props so that the component is as re-usable as possible)
So your parent component could look something like this:
<ApplicationForm v-if="application" #submit="updateApplication" />
<ApplicationForm v-else #submit="createNewApplication" />

Related

Composition API with Nuxt 2 to get template refs array

I'm trying to get the array of element refs that are not in v-for. I'm using #nuxtjs/composition-api on Nuxt 2.
(Truth: I want to make an array of input elements, so that I can perform validations on them before submit)
This sounds too easy on vue 2 as $refs becomes an array when one or more compnents have the same ref name on html. However, this doesn't sound simple with composition api and trying to perform simple task with that got me stuck from long.
So to handle this scenario, I've created 1 composable function. (Soruce: https://v3-migration.vuejs.org/breaking-changes/array-refs.html#frontmatter-title)
// file: viewRefs.js
import { onBeforeUpdate, onUpdated } from '#nuxtjs/composition-api'
export default () => {
let itemRefs = []
const setItemRef = el => {
console.log('adding item ref')
if (el) {
itemRefs.push(el)
}
}
onBeforeUpdate(() => {
itemRefs = []
})
onUpdated(() => {
console.log(itemRefs)
})
return {
itemRefs,
setItemRef
}
}
Here is my vue file:
<template>
<div>
<input :ref="input.setItemRef" />
<input :ref="input.setItemRef" />
<input :ref="input.setItemRef" />
<input :ref="input.setItemRef" />
<input :ref="input.setItemRef" />
<input :ref="input.setItemRef" />
// rest of my cool html
</div>
</template>
<script>
import {
defineComponent,
reactive,
useRouter,
ref
} from '#nuxtjs/composition-api'
import viewRefs from '~/composables/viewRefs'
export default defineComponent({
setup() {
const input = viewRefs()
// awesome vue code here...
return {
input
}
}
})
</script>
Now when I run this file, I don't see any adding item ref logs. And on click of a button, I'm logging input. That has 0 items in the itemRefs array.
What's going wrong?
Nuxt 2 is based on Vue 2, which only accepts strings for the ref attribute. The docs you linked actually refer to new behavior in Vue 3 for ref, where functions are also accepted.
Template refs in Nuxt 2 work the same way as they do in Vue 2 with Composition API: When a ref is inside a v-for, the ref becomes an array:
<template>
<div id="app">
<button #click="logRefs">Log refs</button>
<input v-for="i in 4" :key="i" ref="itemRef" />
</div>
</template>
<script>
import { ref } from '#vue/composition-api'
export default {
setup() {
const itemRef = ref(null)
return {
itemRef,
logRefs() {
console.log(itemRef.value) // => array of inputs
},
}
}
}
</script>
demo
And setup() does not provide access to $refs, as template refs must be explicitly declared as reactive refs in Composition API.

VueJS - V-for doesn't re-render after data is updated and needs page refresh to see the change

So this code does adds or delete an entry, But whenever I add or delete, it does not show the changes or rather re-render. I need to refresh the page in order to see what changes had.
note: I am using ME(Vue)N stack.
I have this code:
<script>
import postService from '../../postService';
export default {
name: 'postComponent',
data() {
return {
posts: [],
error: '',
text: ''
}
},
async created() {
try {
this.posts = await postService.getPosts();
}catch(e) {
this.error = e.message;
}
},
methods: {
async createPost() {
await postService.insertPost(this.text)
this.post = await postService.getPosts();
// alert(this.post,"---")
},
async deletePost(id) {
await postService.deletePost(id)
this.post = await postService.getPosts();
// alert(this.post)
}
}
}
</script>
<template>
<div class="container">
<h1>Latest Posts</h1>
<div class="create-post">
<label for="create-post">input...</label>
<input type="text" id="create-post" v-model="text" placeholder="Create a post">
<button v-on:click="createPost">Post</button>
</div>
<!-- CREATE POST HERE -->
<hr>
<p class="error" v-if="error">{{error}}</p>
<div class="posts-container">
<div class="post"
v-for="(post) in posts"
v-bind:key="post._id"
v-on:dblclick="deletePost(post._id)"
>
{{ `${post.createdAt.getDate()}/${post.createdAt.getMonth()}/${post.createdAt.getFullYear()}`}}
<p class="text">{{ post.username }}</p>
</div>
</div>
</div>
</template>
sorry if there's an error in the snippet. I just needed to show the code and I cant make the script work on the code sample {}.
Any help would be appreciate. Vuejs beginner here.
This code is copied and typed through a youtube tutorial.
Your component has a data property posts, but you're assigning to this.post in several places in the code.
I suspect a typo, but it's also worth remembering that if this additional property (this.post) isn't available when the component is instantiated, it won't be (magically) converted into a reactive property when you create/assign to it.

Return Vue Component in a custom rendering function for a contentful embedded entry

I'm playing with Contentful! and I'm having trouble with Rich text content field.
I'm using '#contentful/rich-text-types' and #contentful/rich-text-html-renderer modules to customize the way this block is rendered and to display some assets and reference linked in Rich text content.
After calling getEntries in nuxt asyncData function, I've a description data available in my page component.
I'm using documentToHtmlString function with options.
Everything is working fine, but I would like to use a component I have already written (Post.vue), instead of returning the template in ES6 Template Strings.
I know that is possible, but I'm quite new to JS world.
I've tried to require components/post/Post.vue, but I don't know how to use it.
import { BLOCKS } from '#contentful/rich-text-types';
import { documentToHtmlString } from "#contentful/rich-text-html-renderer"
Vue component template where rich text field is rendered
<section class="container">
<div class="columns">
<div class="column">
<div v-html="formatContent(description)" />
</div>
</div>
</section>
I simply call formatContent method to call documentToHtmlString as follow (it works):
methods: {
formatContent(content) {
return documentToHtmlString(content, options)
}
}
And customize documentToHtmlString with options as described in doc:
const embeddedEntryRender = (node) => {
const { data: { target: entry} } = node
const fields = entry.fields
const sys = entry.sys
// LOOK HERE
// const postComponent = require('~/components/post/Post')
return `
<div class="column is-4">
<div class="card">
<div class="card-content">
<div class="media">
<div class="media-content">
<h3 class="title is-4">${fields.title}</h3>
<div class="subtitle is-6">${fields.description}</div>
</div>
</div>
<div class="content">
</div>
</div>
</div>
</div> `
}
const options = {
renderNode: {
[BLOCKS.EMBEDDED_ENTRY]: (node) => embeddedEntryRender(node),
// [BLOCKS.EMBEDDED_ASSET]: (node) => `<custom-component>${customComponentRenderer(node)}</custom-component>`
}
}
No errors detected
--
Thanks a lot
yep you can have a custom vue component in there with a different npm library, I had this same problem.
npm i contentful-rich-text-vue-renderer
in template:
<rich-text-renderer :document="document" :nodeRenderers="renderNode" />
where 'document' is the data sent form contentful, looks like your calling it description. RenderNode is a method described below.
in script:
data () {
return {
renderNode: [INLINES.ASSET_HYPERLINK]: (node, key, h) => {
return h('my-vue-component', { key: hey, props: { myProp: 'blah blah' }},'what I want inside the <my-vue-component> tag'`)
}
}
this might be kind of confusing. So First imprt the richTextRenderer component from that npm library and make sure to declare it in the components section of your vue component. (or gloablly)
Next pass into its 'document' prop the contentful rich text field
if you want custom rendering, pass into the nodeRenders prop a function (I had to declare it in the data section)
My example takes any asset hyperlink type and replaces it with a component of what I want inside the tag
I only got this to work if I globally declared the my-vue-component in the main.js file.
import MyVueComponent from 'wherever/it/is';
Vue.component('my-vue-component', MyVueComponent);
there are more configurations for this, just read the npm libs documentation (though its not great docs, it took my a long time to figure out how to pass props down, I had to read their github code to figure that out lol)

Vue.js multiple instances of same component issue

I have created a vue component for selecting photos. When the user clicks any photo the id of the photo will be assigned to a hidden input field inside the component.
Now I have used this component twice on the same page with different data. The problem is when I click on the photo of one component the value of the input field of both the components gets updated. I am using vue.js version 2.1.10
Here is the simplified version of my component.
<div>
<input type="hidden" :name="inputName" :value="currentSelectedPhoto.id">
<div v-for="photo in photos">
<div v-on:click="updateSelectedPhoto(photo)">
<img :src="photo.photo_url" />
</div>
</div>
</div>
The Component
export default {
props: {
...
},
methods: {
getPhotos(){
...
},
updateSelectedPhoto(photo){
this.currentSelectedPhoto = photo;
}
}
}
This is how I am using it in html
<div>
<div>
Profile Photo
<photo-selector
photos="{{ $photos }}"
input-name="profile_photo_id"
>
</photo-selector>
</div>
<div class="col-sm-4">
Cover Photo
<photo-selector
photos="{{ $otherPhotos }}"
input-name="cover_photo_id"
>
</photo-selector>
</div>
</div>
Based on your codepen sample, it's because you are sharing the state object between the two:
const initalState = {
selectedPhoto: null
};
const PhotoSelector = Vue.extend({
data: () => {
return initalState
},
Vue mutates the initial state object (by wrapping it in reactive getters etc), so you need to have data() return a fresh state object for the instance to use:
data: () => {
return {
selectedPhoto: null
};
},

Using POST in React without form?

Lets say I have this code here:
getInitialState:function(){
return { food: 'Chinese' }
},
restaurants:function(){
return (<div><form method="post">
<p>I like <span name="food">{this.state.food}</span> food</p>
<button type="submit">Butane</button>
</form></div>);
},
My only experience with POST so far has been with forms and input fields. So I would like to know how to do this without, using more static content.
In the above example, I have content that isn't derived from an input field. I would like to put the state variable, in this case, Chinese, into a POST request.
Ideally, the button labeled butane submits the info from my state into my POST. And the span name is there to assign it a name for my back-end to read it from.
How would I re-arrange this code to enable use of the state variable in a POST context?
You can add hidden input into form
<div>
<form method="post">
<p>I like <span name="food">{this.state.food}</span> food</p>
<button type="submit">Butane</button>
<!-- Hidden fields -->
<input type="hidden" value={this.state.food}/>
</form>
</div>
Update
Agree with #Rishat to use AJAX call.
For another situation which you want to do a normal POST request but don't want to add any input field to your form. You can use this solution:
JavaScript post request like a form submit
Since you're working with React, chances are you develop a single-page application that doesn't reload nor does it lead a user to another location. To perform a POST request then, you need to do it asynchronously. One of the convenient ways is to use axios for that. The whole component would look like this:
import React, { Component } from 'react';
import axios from 'axios';
class X extends Component {
constructor() {
super();
this.state = {
food: 'Chinese'
};
}
handleSubmit(event) {
const {
food
} = this.state;
event.preventDefault();
// do something with form values, and then
axios.post('https://your/api/endpoint', {
food // + any other parameters you want to send in the POST request
}).then(response => {
// do something with response, and on response
}).catch(error => {
// do something when request was unsuccessful
});
}
restaurants() {
return (
<div>
<form
method="post"
onSubmit={event => this.handleSubmit(event)}>
<p>I like <span name="food">{this.state.food}</span> food</p>
<button type="submit">Butane</button>
</form>
</div>
);
}
}

Categories