thanks a lot for taking a look at my problem.
I've been building a button to handle a Mailchimp API call but I can't seem to be able to piece it all together using useState. I would really appreciate some help with this as it is currently throwing 500 errors when successfully added to the mailing list with new email addresses and the response from Mailchimp seems to be fine.
I know there is probably some sort of react hook or other shortcut I could use but I really want to make this work..! hahaa!
api/subscribe.js
export default function handler(req, res) {
const { email } = req.body;
console.log(`email: ${email}`);
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
try {
const client = require('#mailchimp/mailchimp_marketing');
const API_KEY = process.env.MAILCHIMP_API_KEY;
const API_SERVER = process.env.MAILCHIMP_API_SERVER;
const LIST_ID = process.env.MAILCHIMP_AUDIENCE_ID;
client.setConfig({
apiKey: API_KEY,
server: API_SERVER,
});
const run = async () => {
const response = await client.lists.addListMember(LIST_ID, {
email_address: `${email}`,
status: 'pending',
skip_merge_validation: true,
});
console.log(response);
};
run();
if (response.status >= 400) {
return res.status(400).json({
error: `There was an error subscribing your email address to the newsletter.
Please contact us directly so we can add you in manually. Sorry for any inconvenience.`,
});
}
return res.status(201).json({
message: 'Success! ๐ You are now subscribed to the newsletter.',
});
} catch (err) {
console.log(res.error);
return res.status(500).json({ error: '***ERROR***' });
}
}
My messy but functional code..!
components/Contact.js
import React, { useState } from 'react';
import LoadingSpinner from '../components/LoadingSpinner';
import { CountdownCircleTimer } from 'react-countdown-circle-timer';
export default function Contact() {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
// const [loading, setLoading] = useState(true);
const [state, setState] = useState('IDLE');
const subscribe = async (e) => {
e.preventDefault();
setState('LOADING');
setMessage(null);
try {
const res = await fetch('/api/subscribe', {
body: JSON.stringify({
email: email,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
});
console.log(res);
if (res.status >= 400) {
console.log(res.error);
setState('ERROR');
setMessage(
<div>
An error has occurred, please{' '}
<a
href="/contact"
target="_blank"
rel="noreferrer"
className="text-blue-500 underline cursor-pointer transition-transform duration-7000 hover:text-gray-200"
onClick={() => {
setState('IDLE');
setMessage(null);
setEmail('');
}}
>
contact us
</a>
</div>
);
setEmail('');
setTimeout(() => {
setState('IDLE');
setMessage(null);
}, 10000);
return;
}
setState('SUCCESS');
setMessage('Success! ๐ You are now subscribed to the newsletter.');
setEmail('');
setTimeout(() => {
setState('IDLE');
setMessage(null);
}, 10000);
return;
} catch (e) {
setState('ERROR');
console.log(e.res.error);
setMessage(e.res.error);
setEmail('');
setTimeout(() => {
setState('IDLE');
setMessage(null);
}, 10000);
return;
}
};
return (
<div className="h-[15rem] xs:h-[13.5rem] xsm:h-[12.5rem] sm:h-[13rem] w-full bg-black/90 px-2">
<div className="flex justify-center items-center">
<h1 className="text-center text-zinc-300 text-lg md:text-2xl mt-4">
Sign up to the Newsletter...
</h1>
</div>
<div className="flex justify-center items-center w-full">
<form onSubmit={subscribe}>
<input
type="email"
id="email-input"
name="email"
placeholder="Your#email.here"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autoCapitalize="off"
autoCorrect="off"
aria-autocomplete="list"
className="h-[40px] min-w-[270px] md:min-w-[400px] border border-black/60 rounded-xl w-full text-center text-md px-2"
/>
<div className="flex justify-center items-center py-2">
{state === 'IDLE' && (
<button
type="submit"
value=""
name="subscribe"
disabled={state === 'LOADING'}
className="w-[200px] h-[40px] px-12 mt-2 text-lg border border-black/60 rounded-xl bg-gray-200 text-gray-900 transition-colors duration-700 transform hover:bg-gray-500 hover:text-gray-100"
>
Subscribe
</button>
)}
{state === 'ERROR' && (
<div className="h-[50px]">
<CountdownCircleTimer
isPlaying
size={55}
strokeWidth={2}
duration={10}
trailColor="#3399ff"
rotation="clockwise"
colors="#ffffff"
>
{({ remainingTime }) => remainingTime}
</CountdownCircleTimer>
</div>
)}
{state === 'SUCCESS' && (
<div className="h-[50px]">
<CountdownCircleTimer
isPlaying
size={50}
duration={10}
colors={[
['#004777', 0.33],
['#F7B801', 0.33],
['#A30000', 0.33],
]}
>
{({ remainingTime }) => remainingTime}
</CountdownCircleTimer>
</div>
)}
{state === 'LOADING' && (
<button
type="submit"
value=""
disabled
name="subscribe"
className="w-[200px] h-[40px] px-12 mt-2 text-lg border border-black/60 rounded-xl bg-gray-200 text-gray-900 transition-colors duration-700 transform"
>
<div className="flex justify-center items-center">
<LoadingSpinner />
</div>
</button>
)}
</div>
<div className="text-zinc-300 text-sm md:text-lg text-center md:min-w-[35ch]">
{message
? message
: `We only send emails when we have genuine news.`}
</div>
</form>
</div>
</div>
);
}
response from Mailchimp (with sensitive info taken out)
email: becir28216#jernang.com
undefined
{
id: '',
email_address: 'becir28216#jernang.com',
unique_email_id: '',
contact_id: '',
full_name: '',
web_id: ,
email_type: 'html',
status: 'pending',
consents_to_one_to_one_messaging: true,
merge_fields: { FNAME: '', LNAME: '' },
stats: { avg_open_rate: 0, avg_click_rate: 0 },
ip_signup: '',
timestamp_signup: '2022-11-15T20:46:33+00:00',
ip_opt: '',
timestamp_opt: '',
member_rating: 2,
last_changed: '2022-11-15T20:46:33+00:00',
language: '',
vip: false,
email_client: '',
location: {
latitude: 0,
longitude: 0,
gmtoff: 0,
dstoff: 0,
country_code: '',
timezone: '',
region: ''
},
source: 'API - Generic',
tags_count: 0,
tags: [],
list_id: '',
...}
I want to change the state of the button according to the response from the API call. I have been trying all sorts of combinations and now my head hurts..
Expected behaviour:
When it is idle, button says Subscribe and the normal message is displayed below it.
when it is loading, the button displays the loading spinner and still displays the normal message
When there is an error, the button displays the countdowntimer and the error message.
When the API call is a success, the loading spinner disappears, the success message is displayed and then 10 seconds later, the whole form resets again.
Related
Iโm trying to display a name dynamically, but I get the same name forEach element. What Iโm trying to do is:
<template>
<div class="app__projects">
<div
class="app__projects__container"
v-for="project in visibleProjects"
:key="project.id"
:id="project.id"
>
<div class="app__projects__image">
<img
:src="project.imgUrl"
alt="Project Image"
width="570"
height="320"
loading="lazy"
/>
</div>
<div class="app__projects__content">
<h3>{{ project.name }}</h3>
<p>
{{ project.description }}
</p>
<a
:href="project.link"
target="_blank"
class="app__projects__content-btn"
>
{{ displayNameButton }}
</a>
<hr class="app__projects__content--spacer" />
</div>
</div>
<button
v-if="showMoreProjectsButton"
class="app__projects__showMoreButton"
#click="loadMoreProjects"
>
show more projects
</button>
</div>
</template>
On the I'm trying to display a name dynamically, and all the time the same name is displayed, but I want to display the name based on the computed property that I wrote below.
Here is the visibleProjects:
const visibleProjects = computed(() => {
return storeProjects.projects.slice(0, maxProjectsShown.value);
});
Iโm trying to iterate through an array of objects from the store like:
const displayNameButton = computed(() => {
const isObjPresent = storeProjects.projects.find((o => o.wordpress === 'yes')).wordpress;
console.log(isObjPresent);
if (isObjPresent === 'yes') return 'See Website';
else if (!isObjPresent) return 'See code';
})
The array of objects from the store is:
import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';
export const useProjectsStore = defineStore({
id: 'projects',
state: () => {
return {
projects: [
{
id: uuidv4(),
imgUrl: lightImg,
name: 'use this',
description:
'track of this',
wordpress: false,
},
{
id: uuidv4(),
imgUrl: recogn,
name: 'deep lear',
description:
'I tried my best',
wordpress: โyesโ,
},
...
{},
{},
],
};
},
});
So the problem is with your computed property. It will always return the same value because there is no input based on which the function can determine which string should it returns. Based on the code you already have I think you should write a method that will return desired string.
const displayNameButton = (project) => {
return (project.wordpress === 'yes') ? 'See Website' : 'See code';
})
and in the template
<a
:href="project.link"
target="_blank"
class="app__projects__content-btn"
>
{{ displayNameButton(project) }}
</a>
OR you can modify your visibleProjects:
const visibleProjects = computed(() => {
return storeProjects.projects.slice(0, maxProjectsShown.value).map((e) => {
const project = {...e};
project.wordpress = (project.wordpress === 'yes') ? 'See Website' : 'See code';
return project;
});
});
and in the template
<a
:href="project.link"
target="_blank"
class="app__projects__content-btn"
>
{{ project.wordpress }}
</a>
I am attempting to build a Pokemon filtered search app with Vue 3 and Composition API based on the following tutorial: https://www.youtube.com/watch?v=QJhqr7jqxVo. (GitHub: https://github.com/ErikCH/PokemonVue)
The fetch method used in the search component includes a reduce() function to handle urlIdLookup based on a specific id assigned to each Pokemon in the API response:
const state = reactive({
pokemons: [],
filteredPokemon: computed(()=> updatePokemon()),
text: "",
urlIdLookup: {}
});
fetch("https://pokeapi.co/api/v2/pokemon?offset=0")
.then((res) => res.json())
.then((data) => {
console.log(data);
state.pokemons = data.results;
state.urlIdLookup = data.results.reduce((acc, cur, idx)=>
acc = {...acc, [cur.name]:idx+1 }
,{})
console.log('url',state.urlIdLookup+1)
});
urlIdLookup is then passed into the route used to display selected Pokemon info:
<div
class="ml-4 text-2xl text-blue-400"
v-for="(pokemon, idx) in filteredPokemon"
:key="idx"
>
<router-link :to="`/about/${urlIdLookup[pokemon.name]}`">
{{ pokemon.name }}
</router-link>
</div>
Instead of using the above fetch setup, I wish to use Axios to handle the request and response from the Pokemon API. After installing Axios in the project and importing it into the component, I added a new fetchPokemon method:
const fetchPokemon = () => {
axios.get('https://pokeapi.co/api/v2/pokemon?offset=0')
.then(response => {
state.pokemons = response.data
})
}
onMounted(() => {
fetchPokemon()
})
While using Axios in this new fetch method, I want to handle urlIdLookup similar to the previous fetch setup, but without using the reduce() method and de-structured accumulator, if possible. How can I go about using Axios to retrieve the urlId of each Pokemon, then pass that urlId into the "about" route in the template?
Here is the full component:
<template>
<div class="w-full flex justify-center">
<input placeholder="Enter Pokemon here" type="text"
class="mt-10 p-2 border-blue-500 border-2" v-model="text" />
</div>
<div class="mt-10 p-4 flex flex-wrap justify-center">
<div
class="ml-4 text-2xl text-blue-400"
v-for="(pokemon, idx) in filteredPokemon"
:key="idx"
>
<router-link :to="`/about/${urlIdLookup[pokemon.name]}`">
{{ pokemon.name }}
</router-link>
</div>
</div>
</template>
<script>
import axios from 'axios';
import { reactive, toRefs, computed, onMounted } from "vue";
export default {
setup() {
const state = reactive({
pokemons: [],
filteredPokemon: computed(()=> updatePokemon()),
text: "",
urlIdLookup: {}
});
const fetchPokemon = () => {
axios.get('https://pokeapi.co/api/v2/pokemon?offset=0')
.then(response => {
state.pokemons = response.data
})
}
onMounted(() => {
fetchPokemon()
})
// fetch("https://pokeapi.co/api/v2/pokemon?offset=0")
// .then((res) => res.json())
// .then((data) => {
// console.log(data);
// state.pokemons = data.results;
// state.urlIdLookup = data.results.reduce((acc, cur, idx)=>
// acc = {...acc, [cur.name]:idx+1 }
// ,{})
// console.log('url',state.urlIdLookup+1)
// });
function updatePokemon(){
if(!state.text){
return []
}
return state.pokemons.filter((pokemon)=>
pokemon.name.includes(state.text)
)
}
return { ...toRefs(state), fetchPokemon, updatePokemon };
}
};
</script>
If I understood you correctly take a look at following snippet:
const { reactive, toRefs, computed, onMounted } = Vue
const { axioss } = axios
const app = Vue.createApp({
setup() {
const state = reactive({
pokemons: [],
filteredPokemon: computed(() => updatePokemon()),
text: "",
urlIdLookup: {},
});
const fetchPokemon = () => {
axios
.get("https://pokeapi.co/api/v2/pokemon?offset=0")
.then((response) => {
state.pokemons = response.data.results; // ๐ get just results
});
};
fetchPokemon();
// ๐ function to get index
const getPokemonId = (item) => {
return state.pokemons.findIndex((p) => p.name === item);
};
function updatePokemon() {
if (!state.text) {
return [];
}
return state.pokemons.filter((pokemon) =>
pokemon.name.includes(state.text)
);
}
// ๐ return new function
return { ...toRefs(state), fetchPokemon, updatePokemon, getPokemonId };
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3.2.29/dist/vue.global.prod.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.1/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
<div class="w-full flex justify-center">
<input
placeholder="Enter Pokemon here"
type="text"
class="mt-10 p-2 border-blue-500 border-2"
v-model="text"
/>
</div>
<div class="mt-10 p-4 flex flex-wrap justify-center">
<div
class="ml-4 text-2xl text-blue-400"
v-for="(pokemon, i) in filteredPokemon"
:key="i"
>
<!-- // ๐ call function to get index -->
<router-link :to="`/about/${getPokemonId(pokemon.name)}`">
{{ pokemon.name }} - id {{ getPokemonId(pokemon.name) }}
</router-link>
</div>
</div>
</div>
it seem id is not necessary, why not use name be id. if you want use interger
be must, you can foreach results set index be id to each item, then
<router-link :to="`/about/${pokemon.id}`">
{{ pokemon.name }}
</router-link>
I am trying to save data using Axios API from my front end which is built using the Quasar framework. When I am sending the API request it is responding 400 (Bad Request). SO far what have tried is given in below. I am new to this Framework. So if anyone can help me with this and suggest any good tutorial for learning Quasar then it will be much more helpful for me.
<template>
<q-page>
<div class="row q-col-gutter-sm q-ma-xs q-mr-sm">
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
<q-card
flat
bordered
class
>
<q-card-section>
<div class="text-h6">Add Style Status</div>
</q-card-section>
<q-separator inset></q-separator>
<q-card-section>
<q-form>
<q-list>
<!-- <q-item>
<q-item-section>
<q-input
dense
outlined
v-model="styleStatus.styleStatusId"
label="Style Status Id"
/>
</q-item-section>
</q-item> -->
<q-item>
<q-item-section>
<q-input
dense
outlined
v-model="styleStatus.statusName"
label="Style Status Name"
/>
</q-item-section>
</q-item>
<q-card-actions
align="right"
class="text-teal"
>
<q-btn
:label="styleStatus.styleStatusId==='' ? 'Save' : 'Update' "
type="submit"
color="positive"
v-close-popup
:disabled="!styleStatus.statusName"
icon-right="save"
#click="addNewStyleStatus()"
/>
</q-card-actions>
</q-list>
</q-form>
</q-card-section>
</q-card>
</div>
</div>
</q-page>
</template>
<script>
export default {
data () {
return {
filter: '',
mode: 'list',
styleStatus: {
styleStatusId: '',
statusName: ''
},
pagination: {
rowsPerPage: 10
},
model: null,
data: this.data
}
},
methods: {
addNewStyleStatus () {
if (this.styleStatus.styleStatusId !== '') {
this.updateData()
} else {
this.saveData()
}
},
saveData () {
this.$axios.post('http://192.168.0.11:8020/api/StyleStatuses', this.styleStatus)
.then(res => {
console.log(res)
this.$q.notify({
color: 'positive',
position: 'top-right',
message: 'Record Inserted Successfully',
icon: 'check_circle'
})
this.getAllStyleStatus()
})
.catch(() => {
this.$q.notify({
color: 'negative',
position: 'top-right',
message: 'Oooops!! something was wrong.',
icon: 'report_problem'
})
})
},
updateData () {
this.$axios.put('http://192.168.0.11:8020/api/StyleStatuses/', this.styleStatus)
.then(res => {
this.$q.notify({
color: 'positive',
position: 'top-right',
message: 'Record Updated Successfully',
icon: 'check_circle'
})
this.styleStatus = {}
this.getAllStyleStatus()
})
.catch(() => {
this.$q.notify({
color: 'negative',
position: 'top-right',
message: 'Oooops!! something was wrong.',
icon: 'report_problem'
})
})
},
editData (x) {
this.styleStatus = x.row
}
}
}
</script>
<style scoped></style>
This post is not a question actually.
More like help to the world for people who are struggling with Nuxt.js and SendGrid.
I've been using stackoverflow for such a long time so maybe now it's my turn to start helping others.
I've been working on Nuxt.js WebApp development for the past 8 weeks.
Nuxt.js is a massive learning curve and challenge for me but I really love working with this technology.
I spent the last 2 days developing sending the form with the use of SendGrid. There's not too much help online and I've been struggling a lot but I made it!
So maybe some people will find my post useful.
Here's my form:
<form
v-show="!isSubmitted"
class="contact-us__form"
#submit.prevent="validate">
<b-form-group :class="{'form-group--error': $v.name.$error}">
<b-form-input
id="name"
v-model.trim="$v.name.$model"
type="text"
placeholder="Full Name">
></b-form-input>
<div class="error" v-if="!$v.name.required">Field is required</div>
<div class="error" v-if="!$v.name.minLength">Name must have at least {{$v.name.$params.minLength.min}} letters.</div>
</b-form-group>
<b-form-group :class="{'form-group--error': $v.phone.$error}">
<b-form-input
id="phone"
v-model.trim="$v.phone.$model"
type="number"
placeholder="Phone Number">
></b-form-input>
<div class="error" v-if="!$v.phone.required">Field is required</div>
</b-form-group>
<b-form-group :class="{'form-group--error': $v.email.$error}">
<b-form-input
id="email"
v-model.trim="$v.email.$model"
type="email"
placeholder="Email Address">
></b-form-input>
<div class="error" v-if="!$v.email.required">Field is required</div>
</b-form-group>
<div class="d-flex align-items-end">
<b-form-group :class="{'form-group--error': $v.message.$error}">
<b-form-textarea
id="message"
v-model.trim="$v.message.$model"
type="text"
placeholder="Message"
></b-form-textarea>
<div class="error" v-if="!$v.message.required">Field is required</div>
<div class="error" v-if="!$v.message.minLength">Name must have at least {{$v.message.$params.minLength.min}} characters.</div>
</b-form-group>
<b-form-group>
<b-button
type="submit"
variant="secondary"
v-html="'S'"
:disabled="submitting" />
</b-form-group>
</div>
</form>
script:
export default {
mixins: [validationMixin],
components: {
subscribeBox
},
data() {
return {
map: bgMap,
name: "",
phone: "",
email: "",
message: "",
submitting: false,
isSubmitted: false,
error: false,
}
},
validations: {
name: {
required,
minLength: minLength(4)
},
phone: {
required,
},
email: {
required,
email
},
message: {
required,
minLength: minLength(5)
}
},
methods: {
validate() {
if (this.$v.$invalid || this.$v.$error|| this.submitting) {
this.$v.$touch();
return
}
this.onSsubmit();
},
async onSsubmit() {
this.submitting = true;
this.error = false;
try {
await this.$axios.$post('/api/v1/send-email', {
name: this.name,
phone: this.phone,
email: this.email,
message: this.message,
});
this.submitting = false
this.isSubmitted = true
await new Promise(resolve => setTimeout(resolve, 2500))
} catch(e) {
this.submitting = false
this.error = true
console.error(e)
}
},
},
}
nuxt.config.js
serverMiddleware: ['~/api/v1/send-email.js'],
api/v1/send-email.js (all the API Keys are placed in .env file)
const express = require("express");
const bodyParser = require('body-parser')
const sgMail = require('#sendgrid/mail');
const app = express();
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
app.use(bodyParser.json())
app.post("/", (req, res) => {
let msg = {
to: req.body.email, // Change to your recipient
from: '', // Change to your verified sender
subject: 'Message from ' + req.body.name,
text: 'telephone ' + req.body.phone + ', ' + 'message ' + req.body.message,
}
sgMail
.send(msg)
.then(() => {
return res.status(200).json({ 'message': 'Email sent!' })
})
.catch((error) => {
return res.status(400).json({ 'error': 'Opsss... Something went wrong ' + error })
})
});
module.exports = {
path: "/api/v1/send-email",
handler: app
};
This app is still not finished but the code is working 100%!
I'm new to Nuxt.js so some bits may not look awesome but I'm also happy and open to feedback and suggestions.
Thank you for reading my post and good luck with your project! :)
Hello I use the library view-qrcode-reader for QR Code scan. I try to add a BEEP scan but I do not feel that the library does this kind of thing. So I did the thing manually but it does not work either.
<template>
<div class="container" id="app">
<router-link class="waves-effect waves-light btn" to="/livreur"><i class="material-icons">arrow_back</i>
</router-link>
<div class="row center">
<span v-if="errors" class="card-panel white-text red darken-1"><strong>{{ errors }}</strong></span>
</div>
<div class="row infos">
<span v-if="infos" class="card-panel white-text green green-1"><strong>Email & SMS envoyรฉ ร {{ infos.firstname }} {{ infos.lastname }}</strong></span>
</div>
<br/>
<div class="row">
<qrcode-stream #decode="onDecode"></qrcode-stream>
</div>
</div>
</template>
<script>
var attributes = {
setting: {
soundSrc: '/sounds/beep.mp3'
}
}
export default {
name: 'prepa',
data () {
return {
infos: '',
errors: '',
success: ''
}
},
methods: {
onDecode (decodedString) {
var audio = new Audio(attributes.setting.soundSrc)
audio.play()
this.$http.get('/orders/delivery/prepa/' + decodedString, {headers: {Authorization: `Bearer ${localStorage.token}`}})
.then(request => this.trackingInfos(request))
.catch((request) => this.trackingFail(request))
},
trackingInfos (req) {
if (req.data.error) {
return this.trackingFail(req)
}
this.errors = ''
this.infos = req.data.datas
this.save()
},
trackingFail (req) {
if (req.data.error) {
this.errors = req.data.error
}
},
save () {
this.$http.post('/order_histories', {
location: this.infos.city,
status: '/api/order_statuses/' + this.$preparation,
User: '/api/users/' + localStorage.userId,
orderId: '/api/orders/' + this.infos.orderId,
headers: {Authorization: `Bearer ${localStorage.token}`}
})
.then(request => this.successPrepa(request))
.catch(() => this.failPrepa())
},
successPrepa (req) {
if (req.data.error) {
return this.failPrepa(req)
}
this.errors = ''
this.success = req.status
},
failPrepa (req) {
if (req.data.error) {
this.errors = req.data.error
}
}
}
}
</script>
No beep and an error that appears in the console.
:8080/sounds/beep.mp3:1 GET http://127.0.0.1:8080/sounds/beep.mp3 net::ERR_ABORTED 404 (Not Found)
:8080/#/prepa:1 Uncaught (in promise) DOMException
Thanks for your help.