$route.params.id dont want to give id data when clicking on drink. CocktailDB API, nuxt.js - axios

Hello Im doing a simple cocktailapp to practice nuxt.js and axios with coktailDB API https://www.thecocktaildb.com/api.php. In drinks/index.vue I have listed all drinks with v-for. When clicking on a drink you get to drinks/_id/index.vue page where the full info about the drink will get showed by its ID. Im using $route.params.id and I have tried with this.$route.params.id. No drink info get showed. Its just shows undefined and brackets. How can I get the drink info to be showed by its ID after been clicking on a specific drink? Thanks in advance!
Drinks/index.vue;
<template>
<div>
<div>
<SearchDrink/>
</div>
<div>
<div v-for="drink in drinks" :key="drink.id">
<nuxt-link :to="'drinks/' + id">
<div class="drink">
<p> {{ drink.strDrink
}} </p>
<img :src="drink.strDrinkThumb" alt=""/>
<p>Instructions:</p>
<p> {{ drink.strInstructions }} </p>
<div class="ing"> Ingridients:
<ul>
<li>{{ drink.strIngredient1 }} </li>
<li>{{ drink.strIngredient2 }} </li>
<li>{{ drink.strIngredient3 }} </li>
<li>{{ drink.strIngredient4 }} </li>
<li>{{ drink.strIngredient5 }} </li>
</ul>
</div>
</div>
</nuxt-link>
</div>
</div>
</div>
</template>
<script>
import SearchDrink from '../../components/SearchDrink.vue'
import axios from 'axios'
export default {
components:{
SearchDrink,
},
data(){
return {
drinks: [],
}
},
methods: {
getAllDrinks(){
axios.get('https://thecocktaildb.com/api/json/v1/1/search.php?s=')
.then((response) => {
this.drinks = response.data.drinks
const myDrink = response.data.drinks
console.log(myDrink)
console.log(myDrink.strDrinkThumb)
})
.catch((error) =>{
console.log(error)
})
},
},
created(){
this.getAllDrinks()
},
// methods: {
// searchDrink(){
// if(!this.search){
// return this.drinks
// }else{
// return this.drinks.filter(drink =>
// drink.text.toLowerCase().includes(this.search.
// toLowerCase()))
// }
// }
// },
head(){
return {
title: 'Drinks App',
meta: [
{
hid: 'description',
name: 'description',
content: 'Best place to search a Drink'
}
]
}
}
}
</script>
Drinks/_id/index.vue;
<template>
<div>
<nuxt-link to="/drinks">
Go Back
</nuxt-link>
<h2> {{ drink }} </h2>
<hr>
<small>Drink ID: {{ this.$route.params.id }}</small>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
drink: {}
}
},
methods: {
getAllDrinks(){
axios.get(`www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${this.$route.params.id}`)
.then((response) => {
this.drinks = response.data.drinks
const myDrink = response.data.drinks
console.log(myDrink)
})
.catch((error) =>{
console.log(error)
})
},
},
created(){
this.getAllDrinks()
},
head(){
return {
title: this.drink,
meta: [
{
hid: 'description',
name: 'description',
content: 'Best place to search a Drink'
}
]
}
}
}
</script>

There are quite a few things that be improved here (and the API is a bit messy too).
Here is how I would do it with modern practices.
/pages/drinks/index.vue
<template>
<div>
<div v-for="drink in drinks" :key="drink.idDrink">
<nuxt-link :to="`/drinks/${drink.idDrink}`">
<div class="drink">
<p>{{ drink.strDrink }}</p>
<img width="100px" height="100px" :src="drink.strDrinkThumb" alt="" />
<p>Instructions:</p>
<p>{{ drink.strInstructions }}</p>
<div class="ing">
<p>Ingredients:</p>
<ul>
<li>{{ drink.strIngredient1 }}</li>
<li>{{ drink.strIngredient2 }}</li>
<li>{{ drink.strIngredient3 }}</li>
<li>{{ drink.strIngredient4 }}</li>
<li>{{ drink.strIngredient5 }}</li>
</ul>
</div>
</div>
</nuxt-link>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
drinks: [],
}
},
async fetch() {
await this.getAllDrinks()
},
methods: {
async getAllDrinks() {
try {
const { data } = await axios.get(
'https://thecocktaildb.com/api/json/v1/1/search.php?s='
)
this.drinks = data.drinks
} catch (error) {
console.log('error', error)
}
},
},
}
</script>
/pages/drinks/_id.vue
<template>
<div>
<nuxt-link to="/drinks"> Go Back </nuxt-link>
<h2>{{ drink.strGlass }}</h2>
<hr />
<small>Drink ID: {{ $route.params.id }}</small>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
drink: {},
}
},
async fetch() {
await this.getAllDrinks()
},
methods: {
async getAllDrinks() {
try {
const { data } = await axios.get(
`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${this.$route.params.id}`
)
this.drink = data.drinks[0]
} catch (error) {
console.log('error', error)
}
},
},
}
</script>
Few notes:
I skipped the parts I don't have access to (like your SearchDrink component) or that are not relevant with the current issue
you probably would need to use the axios module
you don't need to import your Nuxt components, it is done for you

Related

Validate multiple selects with a vue Form

I am new to Vue and I am trying to validate a form made by multiple select rendered by a vfor. The date is coming from a Json, simulated mock-server-json.
I can use Vue Vanilla or vee-validate. I saw I could use useFieldArray with vee-validate but I could not make it work.
<template>
<ux-loader v-if="dataArray.length == 0" loading></ux-loader>
<transition name="onEnter">
<div v-if="dataArray.length != 0">
<form #submit.prevent="handleSubmit">
<div class="form">
<div v-for="(data, index) in dataArray" :key="index" class="select">
{{ index }}
<ux-input-a11y-select v-model="form.selected[index]">
<option data-placeholder value="">-- Choisir une valeur --</option>
<option v-for="option in data.option" :key="option" :value="option">{{ option }}</option>
</ux-input-a11y-select>
</div>
</div>
<button class="submit">Valider</button>
</form>
<Modal v-show="isModalVisible" #close="closeModal" />
</div>
</transition>
<div v-if="error != null">{{ error }}</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import Modal from '../components/Modal.vue'
import { UxBtn, UxInputA11ySelect, UxLoader } from '#libui/ux-default-lib'
import getForm from '../composables/getForm.js'
import postForm from '../composables/postForm.js'
UxInputA11ySelect.define()
UxBtn.define()
UxLoader.define()
export default defineComponent({
name: 'FormUser',
components: {
Modal,
},
setup() {
const dataArray = ref([])
const { error, load } = getForm()
const { sendData } = postForm()
load().then((result: any) => {
dataArray.value = result
})
return { sendData, error, dataArray }
},
data() {
return {
isModalVisible: false,
form: {
selected: [],
},
}
},
methods: {
handleSubmit() {
this.isModalVisible = true
},
async closeModal() {
this.isModalVisible = false
console.log(this.form.selected)
console.log(Object.values(this.form.selected))
this.sendData(this.form.selected)
this.$router.push('Display')
},
},
})
</script>
This is my current code. It is working as I can get an object containing the results of the selects but I am wondering if there is a better way of doing it, like in Angular where you get an object with all results without doing anything particular.
Any help appreciated.

Getting a "FB.login() called before FB.init()." when I run this code locally,

I can't seem to be able to login to my app that I'm making when I click on my "Log in with Facebook" button. Also, I'm using React JS. I think it might have something to do with not having REACT_APP_FACEBOOKLOGIN=######### (where ######### is my Facebook Developer ID) inside of a .env file.
import React, { Component } from 'react';
import logo from './logo.png';
import FacebookLogin from 'react-facebook-login';
import Sidebar from "react-sidebar";
import LeaveGroup from "./components/LeaveGroup";
// import firebase from "./utils/firebase.js";
import { GoogleApiWrapper } from 'google-maps-react';
import MapBox from "./components/MapBox";
// import ReactDOM from 'react-dom'
import ChatBox from "./components/ChatBox";
import API from "./utils/API";
import './App.css';
import CreateGroup from './components/CreateGroup/CreateGroup';
require("dotenv").config();
class App extends Component {
constructor(props) {
super(props);
this.state = {
sidebarOpen: true,
name: "",
id: "",
chatText: "",
messagesArray: [],
groupName: "",
};
this.onSetSidebarOpen = this.onSetSidebarOpen.bind(this);
}
onSetSidebarOpen(open) {
this.setState({ sidebarOpen: open });
};
componentDidMount() {
this.loadUsers();
}
loadUsers = () => {
API.getUsers()
.then(res =>
this.setState({ users: res.data }, () => console.log("loadUsers Data: ", res.data))
)
.catch(err => console.log(err));
};
saveUsers = (data) => {
API.saveUser(data)
.then(res =>
console.log(res))
}
handleOnClick = event => {
event.preventDefault();
if (this.state.name) {
API.saveUser({
name: this.state.name,
})
.then(res => this.loadUsers())
.catch(err => console.log(err));
}
};
responseFacebook = (response) => {
console.log(response);
this.setState({ name: response.name, id: response.id })
this.saveUsers(response);
}
render() {
return (
<div className="App">
<Sidebar
sidebar={<b>
<button onClick={() => this.onSetSidebarOpen(false)}>
×
</button>
<div>
<img id="logo-image" src={logo} alt="catchup-app-logo" />
</div>
<div className="about-text">
{/* <p>The CatchUp! app allows you to
create, share and join private location based groups.
</p> */}
</div>
<div
style={{ padding: 40 }}>
<br />
<FacebookLogin
appId={process.env.REACT_APP_FACEBOOKLOGIN}
autoLoad={true}
reauthenticate={true}
fields="name,email,picture"
callback={this.responseFacebook}
/>
<br />
<br />
</div>
{/* Create group box */}
<CreateGroup
groupName={this.state.groupName}
groupMember={this.state.name}
/>
{/* Join group box */}
<div className="text-box">
<p>
<button class="btn btn-dark" type="button" data-toggle="collapse" data-target="#collapseExample1" aria-expanded="false" aria-controls="collapseExample">
Join a Group
</button>
</p>
<div class="collapse" id="collapseExample1">
<div class="card card-body">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Group Name" aria-label="Group Name" aria-describedby="button-addon2" />
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon">Join</button>
</div>
</div>
</div>
</div>
</div>
<ChatBox
name={this.state.name}
groupName={this.state.groupName}
messagesArray={this.state.messagesArray}
/>
</b>}
open={this.state.sidebarOpen}
onSetOpen={this.onSetSidebarOpen}
styles={{ sidebar: { background: "white" } }}
>
<button onClick={() => this.onSetSidebarOpen(true)}>
<i class="fas fa-bars"></i>
</button>
</Sidebar>
<br />
<br />
<MapBox
gProps={this.props.google}
gZoom={17}
gOnMarkerClick={this.gOnMarkerClick}
gName={this.state.name}
gGroupName={this.state.groupName}
gOnClose={this.onInfoWindowClose}
/>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: `${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}`
})(App)
I want this to be able to get this to work so move onto logging in a user into my MongoDB.

Vuejs toggle class in v-for

I'm making a list of items with v-for loop. I have some API data from server.
items: [
{
foo: 'something',
number: 1
},
{
foo: 'anything',
number: 2
}
]
and my template is:
<div v-for(item,index) in items #click=toggleActive>
{{ item.foo }}
{{ item.number }}
</div>
JS:
methods: {
toggleActive() {
//
}
}
How can i toggle active class with :class={active : something} ?
P.S I don't have boolean value in items
You can try to implement something like:
<div
v-for="(item, index) in items"
v-bind:key="item.id" // or alternativelly use `index`.
v-bind:class={'active': activeItem[item.id]}
#click="toggleActive(item)"
>
JS:
data: () => ({
activeItem: {},
}),
methods: {
toggleActive(item) {
if (this.activeItem[item.id]) {
this.removeActiveItem(item);
return;
}
this.addActiveItem(item);
},
addActiveItem(item) {
this.activeItem = Object.assign({},
this.activeItem,
[item.id]: item,
);
},
removeActiveItem(item) {
delete this.activeItem[item.id];
this.activeItem = Object.assign({}, this.activeItem);
},
}
I had the same issue and while it isn't easy to find a whole lot of useful information it is relatively simple to implement. I have a list of stores that map to a sort of tag cloud of clickable buttons. When one of them is clicked the "added" class is added to the link. The markup:
<div class="col-sm-10">
{{ store.name }}
</div>
And the associated script (TypeScript in this case). toggleAdd adds or removes the store id from selectedStoreIds and the class is updated automatically:
new Vue({
el: "#productPage",
data: {
stores: [] as StoreModel[],
selectedStoreIds: [] as string[],
},
methods: {
toggleAdd(store: StoreModel) {
let idx = this.selectedStoreIds.indexOf(store.id);
if (idx !== -1) {
this.selectedStoreIds.splice(idx, 1);
} else {
this.selectedStoreIds.push(store.id);
}
},
async mounted () {
this.stores = await this.getStores(); // ajax request to retrieve stores from server
}
});
Marlon Barcarol's answer helped a lot to resolve this for me.
It can be done in 2 steps.
1) Create v-for loop in parent component, like
<myComponent v-for="item in itemsList"/>
data() {
return {
itemsList: ['itemOne', 'itemTwo', 'itemThree']
}
}
2) Create child myComponent itself with all necessary logic
<div :class="someClass" #click="toggleClass"></div>
data(){
return {
someClass: "classOne"
}
},
methods: {
toggleClass() {
this.someClass = "classTwo";
}
}
This way all elements in v-for loop will have separate logic, not concerning sibling elements
I was working on a project and I had the same requirement, here is the code:
You can ignore CSS and pick the vue logic :)
new Vue({
el: '#app',
data: {
items: [{ title: 'Finance', isActive: false }, { title: 'Advertisement', isActive: false }, { title: 'Marketing', isActive: false }],
},
})
body{background:#161616}.p-wrap{color:#bdbdbd;width:320px;background:#161616;min-height:500px;border:1px solid #ccc;padding:15px}.angle-down svg{width:20px;height:20px}.p-card.is-open .angle-down svg{transform:rotate(180deg)}.c-card,.p-card{background:#2f2f2f;padding:10px;border-bottom:1px solid #666}.c-card{height:90px}.c-card:first-child,.p-card:first-child{border-radius:8px 8px 0 0}.c-card:first-child{margin-top:10px}.c-card:last-child,.p-card:last-child{border-radius:0 0 8px 8px;border-bottom:none}.p-title .avatar{background-color:#8d6e92;width:40px;height:40px;border-radius:50%}.p-card.is-open .p-title .avatar{width:20px;height:20px}.p-card.is-open{padding:20px 0;background-color:transparent}.p-card.is-open:first-child{padding:10px 0 20px}.p-card.is-open:last-child{padding:20px 0 0}.p-body{display:none}.p-card.is-open .p-body{display:block}.sec-title{font-size:12px;margin-bottom:10px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div id="app" class="p-5">
<div class="p-wrap mx-auto">
<div class="sec-title">NEED TO ADD SECTION TITLE HERE</div>
<div>
<div v-for="(item, index) in items" v-bind:key="index" class="p-card" v-bind:class="{'is-open': item.isActive}"
v-on:click="item.isActive = !item.isActive">
<div class="row p-title align-items-center">
<div class="col-auto">
<div class="avatar"></div>
</div>
<div class="col pl-0">
<div class="title">{{item.title}}</div>
</div>
<div class="col-auto">
<div class="angle-down">
<svg aria-hidden="true" focusable="false" data-prefix="far" data-icon="angle-down" role="img"
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"
class="svg-inline--fa fa-angle-down fa-w-10 fa-3x">
<path fill="currentColor"
d="M151.5 347.8L3.5 201c-4.7-4.7-4.7-12.3 0-17l19.8-19.8c4.7-4.7 12.3-4.7 17 0L160 282.7l119.7-118.5c4.7-4.7 12.3-4.7 17 0l19.8 19.8c4.7 4.7 4.7 12.3 0 17l-148 146.8c-4.7 4.7-12.3 4.7-17 0z"
class=""></path>
</svg>
</div>
</div>
</div>
<div class="p-body">
<div class="c-card"></div>
<div class="c-card"></div>
<div class="c-card"></div>
</div>
</div>
</div>
</div>
</div>

Mutliple Modals in same page Vuejs 2

I'm a newbie in Vuejs (i'm learning).
I'm trying to do many modals in same page using Vuejs2
Like many people, i have this console warning :
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated:
I read the official doc. I understand that i'm trying to mutating a props and now with vuejs2 its no longer possible.
I tried by using data and computed methods but still doesn't work.
I know the props are now in one way and i think that i understood i need to $emit some props
Here my code:
app.js
Vue.component('modal', Modal);
Vue.component('modal-add-equipe', ModalContent);
Vue.component('modal-user-team', ModalContentTeamUser);
new Vue({
delimiters: ['${', '}'],
el: '#app',
data: {
showModal: false,
showModalAddEquipe: false,
showModalUserTeam: false
},
methods: {
openModal: function(name) {
console.log(this.$refs[name]);
this.$refs[name].show = true;
//this.showModal = true;
},
closeModal: function(name) {
this.$refs[name].show = false;
//this.showModal = false;
}
}
})
Modal.vue
<template>
<transition name="modal">
<div class="modal-mask" #click="close" v-show="show">
<div class="modal-wrapper">
<div class="modal-container with-border" #click.stop>
<slot></slot>
</div>
</div>
</div>
</transition>
</template>
<script>
export default {
props: ['show', 'onClose'],
methods: {
close: function () {
this.onClose();
}
},
ready: function () {
document.addEventListener("keydown", (e) => {
if (this.show && e.keyCode == 27) {
this.onClose();
}
});
}
}
</script>
ModalContent.vue
<template>
<modal :show.sync="show" :on-close="close">
<div class="modal-header">
<slot name="header">
default header
</slot>
</div>
<div class="modal-body">
<slot name="body">
default body
</slot>
</div>
<div class="modal-footer">
<slot name="footer">
</slot>
</div>
</modal>
</template>
<script>
var Modal = require('./Modal.vue');
export default {
props: ['show'],
methods: {
close: function () {
this.$emit('close', false);
},
},
components:{
'modal': Modal
}
}
</script>
the call in twig :
{% for user in usersTeamed %}
<span #click="openModal('userTeam{{ user.getId() }}')"><strong>Equipes</strong></span>
<modal-user-team ref="userTeam{{ user['id'] }}" :show.sync="showModal" #close="closeModal('userTeam{{ user['id'] }}')">
<h3 slot="header">{{ 'equipe_modal_user_equipe'|trans }}</h3>
<div slot="body">
{{ form_start(formUsersTeamed[user['id']]) }}
{{ form_rest(formUsersTeamed[user['id']]) }}
{{ form_end(formUsersTeamed[user['id']]) }}
</div>
</modal-user-team>
{% endfor %}
My goal it's to open one modal (but many in same page and avoid 1k variables like do the example https://v2.vuejs.org/v2/examples/modal.html ) find by "rel"
This code is working but i have console worning !
If someone can help me please :)
PS: I use also gulp with vueify, babelify and aliasify
PS2 : Sorry for my english

Show loading image on each api call till response comes in axios library globally

Sometimes, when we call an api,it takes long time to respond so we prefer to show loading image till response come.
there is start and end event in ajax request to show loading image , I want same kind of stuff in axios.
I want to make it globally for each request in axios library for react.
please suggest me something for this.
import React, {Component} from 'react';
import axios from 'axios';
import loading from '../loading.gif' // relative path to image
class Home extends Component {
constructor() {
super()
this.state = {
time: null,
loading: true,
retJobs: []
}
this.getJobs();
}
getJobs() {
axios.get('http://example.com/getData.php')
.then(response => {
this.setState({retJobs: response.data});
console.log(response);
console.log(this.state.retJobs.results.length);
console.log(this.state.retJobs.results);
this.setState({
time: response.data.time,
loading: false
});
})
.catch(function (error) {
console.log(error);
});
}
render() {
let content;
if (this.state.loading) {
content = <img src={loading} alt="loading"/>// or another graceful content
} else {
content = <p className="jobCount">Found {this.state.retJobs.results.length} Jobs</p>;
}
return (
<div>
<h4>Home</h4>
<div className="App-intro">
<div className="container">
<div className="row mainContent">
<div className=" row mainContent">
{content}
{this.state.retJobs.results && this.state.retJobs.results.map(function (item, idx) {
return <div key={idx} className="col-lg-12">
<div className="jobs">
<div className="row jobHeader">
<div className="col-lg-6">
<h1>{item.jobTitle}</h1>
</div>
<div className="col-lg-6">
<h3>{item.locationName}</h3>
</div>
</div>
<div className="row">
<div className="col-lg-2">
<h2>{item.employerName}</h2>
</div>
<div className="col-lg-10">
<p>{item.jobDescription}</p>
</div>
</div>
</div>
</div>
})}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Home;