Airtable data into Vue.js - vue.js

I am new to vue js and have been trying for hours to get airtable data into my application. I am hoping someone could help me as I feel I am almost there! I am using the Airtable NPM package to retrieve the data - https://www.npmjs.com/package/airtable
<template>
<section id="cards-section" class="cards-section">
<div class="centered-container w-container">
<h1>{{ msg }}</h1>
<div class="cards-grid-container">
<Card />
<ul id="example-1">
<li v-for="item in recordsList" v-bind:key="item">
data here {{ item }}
</li>
</ul>
</div>
</div>
</section>
</template>
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",
components: {
Card,
},
props: {
msg: String,
},
data() {
return {
recordsList: [],
};
},
mounted() {
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",
})
.firstPage(function (err, records) {
if (err) {
console.error(err);
return;
}
records.forEach( (record) => {
console.log(record.get("Name"));
return record.get("Name")
});
});
},
};
</script>
<style scoped>
</style>

Looking at your code you are probably at the stage that you have succesfully retrieved the data from airtable and seeing some records in your console.log.
Now how to get them from inside that function to your Vue instance:
I will show you two ways to go about this and explain them later:
Method 1: Using a reference to self.
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",
components: {
Card,
},
props: {
msg: String,
},
data() {
return {
recordsList: [],
};
},
mounted() {
// create a reference to this vue instance here.
var self = this;
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",
})
.firstPage(function (err, records) {
if (err) {
console.error(err);
return;
}
// now we can set the recordList of our
// vue instance:
self.recordsList = records;
});
},
};
</script>
Method 2: Using javascript arrow function:
<script>
import Card from "../components/Card.vue";
import Airtable from "airtable";
export default {
name: "Main",
components: {
Card,
},
props: {
msg: String,
},
data() {
return {
recordsList: [],
};
},
mounted() {
// no need to create a reference this time.
const base = new Airtable({ apiKey: "******" }).base(
"******"
);
base("Table 1")
.select({
view: "Grid view",
})
.firstPage( (err, records) => {
if (err) {
console.error(err);
return;
}
this.recordsList = records;
});
},
};
</script>
Now what was the problem? In the first example we use a normal javascript anonymous function. this inside a normal javascript anonymous function is not what you expect it to be. We solve this by defining a reference to this (var self = this) somewhere and instead of trying this.recordsList we do self.recordsList inside our anynomous function.
Nem improvements to the javascript language introduced another type of function, the arrow function. One benefit of this function is that this inside this function is the object that you've defined it in. So, this is our vue instance. Now we don't have a problem and can just set this.recordsList.
Other solutions i've ommitted are:
Using Function.bind
async/await

Related

How to get vuex pagination to be reactive?

I am not sure what the problem is. I am creating a Vue/Vuex pagination system that calls my api to get my list of projects. The page initially loads all the projects in when the page is mounted. The Vuex does the inital call with axios. Vuex finds the projects and the number of pages. Once the user clicks on the pagination that is created with the pagination component, it should automatically change the projects for page 2...3 etc.
The problem I have is that it is not reactive until you press the page number twice. I am using vue 3. I have tried not using Vuex and that was successful. I am trying to create a single store that does all the axios calls. Thanks for all your help!
Vuex store
import { createStore } from 'vuex';
import axios from 'axios';
/**
* Vuex Store
*/
export const store = createStore({
state() {
return {
projects: [],
pagination: {}
}
},
getters: {
projects: state => {
return state.projects;
}
},
actions: {
async getProjects({ commit }, page = 1) {
await axios.get("http://127.0.0.1:8000/api/guest/projects?page=" + page)
.then(response => {
commit('SET_PROJECTS', response.data.data.data);
commit('SET_PAGINATION', {
current_page: response.data.data.pagination.current_page,
first_page_url: response.data.data.pagination.first_page_url,
prev_page_url: response.data.data.pagination.prev_page_url,
next_page_url: response.data.data.pagination.next_page_url,
last_page_url: response.data.data.pagination.last_page_url,
last_page: response.data.data.pagination.last_page,
per_page: response.data.data.pagination.per_page,
total: response.data.data.pagination.total,
path: response.data.data.pagination.path
});
})
.catch((e) => {
console.log(e);
});
}
},
mutations: {
SET_PROJECTS(state, projects) {
state.projects = projects;
},
SET_PAGINATION(state, pagination) {
state.pagination = pagination;
}
},
});
Portfolio Component
<template>
<div>
<div id="portfolio">
<div class="container-fluid mt-5">
<ProjectNav></ProjectNav>
<div class="d-flex flex-wrap overflow-auto justify-content-center mt-5">
<div v-for="project in projects" :key="project.id" class="m-2">
<Project :project="project"></Project>
</div>
</div>
</div>
</div>
<PaginationComponent
:totalPages="totalPages"
#clicked="fetchData"
></PaginationComponent>
</div>
</template>
<script>
import Project from "../projects/Project.vue";
import PaginationComponent from "../pagination/PaginationComponent.vue";
import ProjectNav from "../projectNav/ProjectNav.vue";
/**
* PortfolioComponent is where all the projects are displayed.
*/
export default {
name: "PortfolioComponent",
data() {
return {
location: "portfolio",
projects: []
};
},
components: {
Project,
PaginationComponent,
ProjectNav,
},
mounted() {
this.fetchData(1);
},
computed: {
totalPages() {
return this.$store.state.pagination.last_page;
},
},
methods: {
fetchData(page) {
this.$store.dispatch("getProjects", page);
this.projects = this.$store.getters.projects;
},
},
};
</script>
In your fetchData method you are calling the async action getProjects, but you are not waiting until the returned promise is resolved.
Try to use async and await in your fetchData method.
methods: {
async fetchData(page) {
await this.$store.dispatch("getProjects", page);
this.projects = this.$store.getters.projects;
},
},

Why action of Vuex returns a promise<pending>?

I have an action in Vuex actions which commit a mutation that it take a payload from the component, that is a number of the index for returning an object, it works fine on Vuex js file meaning that shows the selected item on the console, as I said it gets index from the payload,
but on the component, it gives me Promise <Pending>, why that's happening? for now, I do not use any API for my Nuxt/Vue app, but I will, and for now, I just want to know why this is happening and what is the best solution for solving this
Here my Vuex codes:
export const state = () => ({
articles: [
{
uid: 0,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/1.jpg',
link: '/articles/1',
},
{
uid: 1,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/2.jpg',
link: '/articles/2',
},
],
})
export const getters = {
getArticles(state) {
return state.articles
},
}
export const mutations = {
getSpeceficArticle(state, payload) {
return state.articles[payload]
},
}
export const actions = {
getSpeceficArticle({ commit }, payload) {
commit('getSpeceficArticle', payload)
},
}
and here my component codes:
<template>
<div class="article">
{{ getSpeceficArticle() }}
<div class="article__banner">
<img src="" alt="" />
</div>
<div class="article__text">
<p></p>
</div>
</div>
</template>
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
// computed: {},
methods: {
async getSpeceficArticle() {
return await this.$store.dispatch('articles/getSpeceficArticle', 0)
},
},
}
</script>
actions are used to update the state they are like mutations but the main difference between them is that actions can include some asynchronous tasks, if you want to get a specific article at given index you should use a getter named getArticleByIndex :
export const getters = {
getArticles(state) {
return state.articles
},
getArticleByIndex:: (state) => (index) => {
return state.articles[index]
}
}
then define a computed property called articleByIndex :
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.$store.getters.articles.getArticleByIndex(0)
}
},
methods: {
},
}
</script>
#Mohammad if you find yourself using a lot of getters/actions etc from Vuex and they're starting to get a little wordy, you can bring in mapGetters from Vuex and rename your calls to something a little more convenient. So your script would become,
<script>
import { mapGetters } from 'vuex'
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.getArticleByIndex(0)
}
},
methods: {
...mapGetters({
getArticleByIndex: 'articles/getArticleByIndex',
})
},
}
</script>
You can add ...mapGetters, ...mapActions to your computed section also.
since there is no web service call in vuex action, try to remove async and await keywords from the component.
Later when you add a webservice call than you can wrap action body in new Promise with resolve and reject and then you can use async and await in component. let me know if this works for you.

Show HTML content with events, loaded from the backend in Vue template

I need to show an image and HTML content with events in the template.
The HTML of the template comes in part from the backend and I need to do a treatment on the front end.
I need to put an image in the new HTML.
I'm doing it this way, but it doesn't work.
The image is always empty.
<template>
<div
v-html="resultado"
></div>
</>
data: ()=>({
resultado:null
}),
mounted(){
fillElement();
},
computed:{
getImage() {
return require("#/assets/pdf.png");
},
},
methods:{
fillElement(){
//get html from backend
const ohtml=getHtmlFrmBackEnd();
let p1 = `<div>Image<img :src='getImage()'></img>${ohtml}</div>`;
this.resultado = p1;
},
}
Solution:
<template>
<div>
<component :is="resultado"></component>
</div>
</template>
<script>
import Vue from "vue";
export default {
data: () => {
return {
resultado: null
};
},
computed: {
compiledData() {
return {
resultado: null
};
}
},
methods: {
delay() {
//making a backend call
return new Promise(resolve => {
setTimeout(() => {
resolve(
"<input type='button' name='btnVoltar' id='btnVoltar' value=' Voltar ' class='button' v-on:click='fVoltar()'>"
);
}, 1000);
});
},
replace(content) {
this.resultado = Vue.component("template-from-server", {
template: content,
methods: {
fVoltar() {
console.log("click");
}
}
});
},
async fillElement() {
//get html from backend
const ohtml = await this.delay();
let p1 = `<div>Image<img src='${require("#/assets/logo.png")}'></img>${ohtml}</div>`;
this.replace(p1);
}
},
mounted() {
this.fillElement();
}
};
</script>
Working Code Example
You can see I loaded the image directly into the src and called fillElement() with this keyword in the mounted() hook.
I also added a delay function to demonstrate a request to the backend.
Edit:
In order to handle events coming with the template from the backend, I created a mini component within the current component that will get rendered once the content is passed. For that, I had to locally import Vue.
Please keep in mind that you will need to replace onclick with #click or v-on:click. You can use regex for that as you have done so already.

How make json data available for my Vue dynamic routes

I have a List component where I fetch my date from db/blogs.json:
created() {
fetch('http://localhost:3000/blogs')
.then(response => {
return response.json();
})
.then(data => {
this.blogs = data;
})
},
In my BlogDetail.vue I have:
<script>
export default {
data: () => {
return {
blogId:this.$route.params.id
}
},
computed: {
blog() {
return this.blogs.find(
blog => blog.id === this.blogId
)
}
}
}
</script>
But how do I get the blogs data in this component, which I fetched in the List component?
Because now in the <template> section of my BlogDetail.vue I cannot access e.g. {{ blog.name }}
Update:
I try passing blogs with props:
Now I am accepting a prop in BlogDetails.vue:
props: {
blogs: {
type: Array
}
},
But from where (which component), I have to registering the prop like :blogs="blogs"?
Update 2:
This is what I have so far, link to the sandbox
Here is the working sandbox.
Firstly you need to import JSON data from your JSON file correctly. As:
<script>
import ListItem from "./ListItem";
import Blogs from "../../public/db/blogs.json";
export default {
name: "List",
components: {
ListItem
},
data() {
return {
blogs: Blogs.experiences
};
},
created() {}
};
</script>
Have to send props in the router-link as :
<router-link
:to="{ name: 'BlogDetails', params: { id: blog.id,blog:blog }}">More information
</router-link>
You can send props to the child component in the tag name, in your case:
//LIST component(PARENT)
<tamplate>
<BlogDetail :blogs="blogs"></BlogDetail> //CHILD component
</template>

vue.js $emit not received by parent when multiple calls in short amount of time

I tried to implement a simple notification system with notification Store inspired by this snippet form Linus Borg : https://jsfiddle.net/Linusborg/wnb6tdg8/
It is working fine when you add one notification at a time, but when you add a second notification before the first one disappears the notificationMessage emit its "close-notification" event but the parent notificationBox component does not execute the "removeNotification" function. removeNotification is called after the emit if you use the click event on the notification though. So there is probably a issue with the timeout but i can't figure out what.
NotificationStore.js
class NotificationStore {
constructor () {
this.state = {
notifications: []
}
}
addNotification (notification) {
this.state.notifications.push(notification)
}
removeNotification (notification) {
console.log('remove from store')
this.state.notifications.splice(this.state.notifications.indexOf(notification), 1)
}
}
export default new NotificationStore()
App.vue
<template>
<div id="app">
<notification-box></notification-box>
<div #click="createNotif">
create new notification
</div>
</div>
</template>
<script>
import notificationMessage from './components/notificationMessage.vue'
import notificationBox from './components/notificationBox.vue'
import NotificationStore from './notificationStore'
export default {
name: 'app',
methods: {
createNotif () {
NotificationStore.addNotification({
name: 'test',
message: 'this is a test notification',
type: 'warning'
})
}
},
components: {
notificationMessage,
notificationBox
}
}
</script>
notificationBox.vue
<template>
<div :class="'notification-box'">
<notification-message v-for="(notification, index) in notifications" :notification="notification" :key="index" v-on:closeNotification="removeNotification"></notification-message>
</div>
</template>
<script>
import notificationMessage from './notificationMessage.vue'
import NotificationStore from '../notificationStore'
export default {
name: 'notificationBox',
data () {
return {
notifications: NotificationStore.state.notifications
}
},
methods: {
removeNotification: function (notification) {
console.log('removeNotification')
NotificationStore.removeNotification(notification)
}
},
components: {
notificationMessage
}
}
</script>
notificationMessage.vue
<template>
<div :class="'notification-message ' + notification.type" #click="triggerClose(notification)">
{{ notification.message }}
</div>
</template>
<script>
export default {
name: 'notificationMessage',
props: {
notification: {
type: Object,
required: true
},
delay: {
type: Number,
required: false,
default () {
return 3000
}
}
},
data () {
return {
notificationTimer: null
}
},
methods: {
triggerClose (notification) {
console.log('triggerClose')
clearTimeout(this.notificationTimer)
this.$emit('closeNotification', notification)
}
},
mounted () {
this.notificationTimer = setTimeout(() => {
console.log('call trigger close ' + this.notification.name)
this.triggerClose(this.notification)
}, this.delay)
}
}
</script>
thanks for the help
my small fiddle from back in the days is still making the rounds I see :D
That fiddle is still using Vue 1. In Vue 2, you have to key your list elements, and you tried to do that.
But a key should be a unique value identifying a data item reliably. You are using the array index, which does not do that - as soon as an element is removed, indices of the following items change.
That's why you see the behaviour you are seeing: Vue can't reliably remove the right element because our keys don't do their job.
So I would suggest to use a package like nanoid to create a really unique id per notification - but a simple counter would probably work as well:
let _id = 0
class NotificationStore {
constructor () {
this.state = {
notifications: []
}
}
addNotification (notification) {
this.state.notifications.push({ ...notification, id: _id++ })
}
removeNotification (notification) {
console.log('remove from store')
this.state.notifications.splice(this.state.notifications.indexOf(notification), 1)
}
}
and in the notification component:
<notification-message
v-for="(notification, index) in notifications"
:notification="notification"
:key="notification.id"
v-on:closeNotification="removeNotification"
></notification-message>