Error recognizing v-model posts in vuejs3 QuillEditor - vuejs3

Binding vmodel="" in vuejs3 QuillEditor post is invalid in quillEditor
If you give the form's internal description:null invalid object error and an empty value description: '' , the post will always be written, but the post will always be empty. Do you know how to solve it?
<template>
<form #submit.prevent="formCreate()">
<div class="in_title contents">
<QuillEditor
v-model="form.description"
style="height:400px;"
theme="snow" />
</div>
<button
class="writing_btn writing_done">
submit
</button>
</form>
</template>
<script>
const form = ref({
title: null,
description: null
})
onst formCreate = async (id) => {
let token = sessionStorage.getItem('access_token')
const data = {
title: form.value.title,
description: form.value.description,
}
console.log(form)
try {
await axios.post('http://127.0.0.1:8000/jobs/create-job/', data, {
headers: {
'Content-Type': 'application/json' ,
'Authorization' : token ,
},
withCredentials:true,
params:{
id
}
})
</script>

Related

Which is the best way to render dynamic items in NextJS?

I´m am new to NextJS and i am finding difficult to understand the difference between getSaticProps and getServerSideProps.
I have a page with a form to add a new event and store it in a json file:
import React from 'react'
import Layout from '#/components/Layout'
import styles from '#/styles/AddEvent.module.css'
export default function AddEventPage() {
const submitHanlder = (e) => {
e.preventDefault();
const formData = {
title: e.target.title.value,
description: e.target.description.value
}
fetch('/api/events', {
method: 'POST',
body: JSON.stringify(formData)
});
console.log(formData)
}
return (
<Layout title='Add New Event'>
<h1>Add Event</h1>
<div className={styles.container}>
<form className={styles.form} action="" onSubmit={submitHanlder}>
<label className={styles.label} >Title</label>
<input type="text" name="title" />
<label className={styles.label} >Description</label>
<input type="text" name="description"/>
<label className={styles.label}htmlFor="">Date</label>
<input type="date" />
<button type='submit' >Submit</button>
</form>
</div>
</Layout>
)
}
This is my api:
const handler = async (req , res) => {
if(req.method === 'POST'){
await fetch('http://localhost:3001/events', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: req.body
})
return res.status(201).json({ message: 'evento agregado' });
}
return res.status(400).json({ error: 'no se pudo agregar el evento' });
}
export default handler;
And i am storing my data in my db.json:
{
"events": [
{
"id": 1,
"title": "Recital coldplay",
"description": "Recital de coldplay en River"
},
{
"title": "Recital metalica",
"description": "Recital de metalica en velez",
"id": 2
}
]
}
Until now i am rendering my events as i used to do it in react.js by importing the {events} and doing a map function, and it works:
import React from 'react'
import Layout from '#/components/Layout'
import { events } from '../../db.json'
export default function EventsPage({ }) {
return (
<Layout>
<h1>My Events</h1>
<div>
{events.map((event) => {
return (
<div>
<h1>{event.title}</h1>
<p>{event.description}</p>
</div>)
})}
</div>
</Layout>
)
}
This works perfectly fine but i know nextjs provides different methods to make this easier? Which method should i use to optimize my code? Can anyone give an example? Is there any step of my code i could avoid?
getServerSideProps is essentially SSR for the page which executes per request.
getStaticProps is static site generation at build time (plus on a timed interval).
You could use either mechanism to read from your json file server side and pass the content in as props.

How to upload an image in cloudinary using a signed upload preset with nextjs?

I am trying to upload a single image file in cloudinary with Next.js.
I tried appending the API key, timestamp, the file to be uploaded. But it results in a post error.
This is the error I get when executing the following code?
POST https://api.cloudinary.com/v1_1/<cloud-name>/image/upload/ 400 (Bad Request)
AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
What did I miss?
export default function Home() {
const [img, setImg] = useState("");
const updateImage = (e) => {
setImg(e.target.files[0]);
};
const uploadImage = async (e) => {
e.preventDefault();
const data = new FormData();
const timestamp = new Date().getTime();
data.append("file", img);
data.append("upload_preset", "cloudinary_default");
data.append("api_key", "<api-key>");
data.append("timestamp", timestamp);
try {
const response = await axios.post(
`https://api.cloudinary.com/v1_1/<cloud-name>/image/upload/`,
data
);
} catch (error) {
console.log(error);
}
};
return (
<form className="text-center my-1 border p-1">
<input type="file" onChange={updateImage} />
<button className="border rounded-md p-1" onClick={uploadImage}>Upload</button>
</form>
);
}

How to populate FormKit input fields with dynamic data fetched from a database

I'm making a fullstack app with vue3, axios using FormKit. For editing existing records I want to populate the input fields with the current data fetched from a mysql database. I stripped down the code to everything needed to display my problem, which in this code example is populating the FormKit input field with the lotnumber I fetched via the asynchronous function "getLotById". The lotnumber appears in the paragraph section but not in the input field. How can I properly delay the rendering of the FormKit element until the lotnumber has been fetched? Here's my code:
<script>
// import axios
import axios from "axios";
export default {
name: "LotEdit",
data() {
return {
lotnumber: this.lotnumber
}
},
props: {
lotid: Number
},
created: async function () {
await this.getLotById();
},
methods: {
// Get Lot By Id
async getLotById() {
try {
const response = await axios.get(`http://localhost:5000/lot/${this.$route.params.id}`);
this.lotnumber = response.data.lotnumber;
console.log(response.data);
}
catch (err) {
console.log(err);
}
},
}
};
</script>
<template>
<div>
<FormKit
type="text"
name="lotnumber"
label="lotnumber"
placeholder=""
validation="required"
:value="lotnumber"
/>
</div>
<div>
<p> Here the lotnumber appears: {{ lotnumber }}</p>
</div>
</template>
I suggest using a v-model on the FormKit input. Because it is two-way bound it means as soon as the async/await completes the data is populated on the template too. Something like...
<FormKit
v-model="lotnumber"
type="text"
name="lotnumber"
label="lotnumber"
placeholder=""
validation="required"
:value="lotnumber"
/>
Getting a little smarter I managed to solve the problem in the following way:
<script>
// import axios
import axios from "axios";
export default {
name: "LotEdit",
data() {
return {
lotnumber: this.lotnumber
}
},
props: {
lotid: Number
},
mounted: async function () {
const response = await this.getLotById();
const node = this.$formkit.get('lotnumber')
node.input(response.data.lotnumber, false)
},
methods: {
// Get Lot By Id
async getLotById() {
try {
const response = await axios.get(`http://localhost:5000/lot/${this.$route.params.id}`);
console.log(response.data);
return response;
}
catch (err) {
console.log(err);
}
},
}
};
</script>
<template>
<div>
<FormKit
type="text"
id="lotnumber"
name="lotnumber"
label="lotnumber"
placeholder=""
validation="required"
:value="lotnumber"
/>{{ lotnumber }}
</div>
</template>
Feel free to post any recommendations as I'm not a pro yet...
I'm also still figuring out how to handle controlled forms but I guess an alternative way to do it is with Form Generation
<script>
export default {
// ...
async setup() {
try {
const response = await axios.get(`http://localhost:5000/lot/${this.$route.params.id}`);
const schema = [
{
$formkit: "text",
label: "Lot Number",
value: response.data.lotnumber,
validation: "required",
},
];
} catch (err) {
console.log(err);
}
return { schema }
}
// ...
}
</script>
<template>
<FormKit type="form">
<FormKitSchema :schema="schema" />
</FormKit>
</template>

Getting the following error: Unhandled Runtime Error SyntaxError: Unexpected end of input

I am trying to send info to the backend(node.js express server) from the frontend(next.js) with the react hook form lib.
const test = () =>{
const { register, handleSubmit, watch, formState: { errors } } = useForm();
const onSubmit = async data => {
const result = await fetch('http://localhost:5000/test', {mode: 'no-cors'},{
method: 'POST',
body: JSON.stringify(data),
headers: {'content-type': 'application/json'}
}).then(res=>res.json())
console.log(data);
}
return(
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("example")} />
<input type="submit" />
</form>
</div>
);
}
export default test;
and this simple .post request on the backend:
app.get('/', (req, res)=>{
res.send('test success');
})
the error is on the following line: }).then(res=>res.json())

Firebase UpdateEmail returning updateEmail failed: First argument "email" must be a valid string

I have a email field in my vue js componont. When the component loads its taking the email value what i have added during the registration time. But when I tried to update my email to a new emai using updateEmail its retruning an error code: "auth/argument-error", message: "updateEmail failed: First argument "email" must be a valid string.".
<template>
<div>
<form #submit.prevent="onUpdateProfile">
<input type="email" v-model="profile.email" placeholder="Enter Your Email..." class="from-input" />
<button type="submit">submit</button>
</form>
</div>
</template>
data() {
return {
profile: {
email: ""
}
};
},
methods:{
onUpdateProfile() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
user.updateEmail({
email: this.profile.email
})
.then(() => {})
.catch(error => {
console.log(error);
});
}
}
},
created() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.profile.email = user.email;
}
}
}
can you try changing this
user.updateEmail({
email: this.profile.email
})
to this?
user.updateEmail(this.profile.email)

Resources