Getting yoast meta data title description into Nuxt - json

Hi I am trying to pull the metadata for each page from WordPress to Nuxt site
This is the home page json file https://pbiss.ac.th/wp-json/wp/v2/pages/17445
And in Nuxt I am using
created() {
axios
.get(`https://pbiss.ac.th/wp-json/wp/v2/pages/17445`)
.then((response) => {
// JSON responses are automatically parsed.
this.metaData = response.data
})
.catch((e) => {
console.log()
})
},
head() {
if (this.metaData) {
const metaArray = []
this.metaData.yoast_meta.map((ele) => {
if (ele.property === 'og:url') {
metaArray.push({
hid: ele.name ? ele.name : ele.property,
name: ele.name ? ele.name : ele.property,
content: 'http://www.pbiss.ac.th/',
})
} else {
metaArray.push({
hid: ele.name ? ele.name : ele.property,
name: ele.name ? ele.name : ele.property,
content: ele.content,
})
}
})
return {
title: this.metaData.yoast_title,
meta: metaArray.yoast_meta,
}
}
},
However, it seems to use the same description and title for all pages, I have added the same code for each page on the site and change the page id, why is it not using the other data?
This is the data I would like to display dynamically
json data

Related

Accessing Vuex Store Before Page Load NuxtJS

Context: I am trying to get Google Maps place data via the place_id on the beforeEnter() route guard. Essentially, I want the data to load when someone enters the url exactly www.example.com/place/{place_id}. Currently, everything works directly when I use my autocomplete input and then enter the route but it does not work when I directly access the url from a fresh tab. I've been able to solve this using the beforeEnter() route guard in traditional Vue, but cannot solve for this using Nuxt. Please help!
Question: How can I access the Vuex Store before a page loads in Nuxt?
Error: Any solution I try (see below) I either end up with a blank page or the page will not load (I think it is stuck in a loop and cannot resolve the Promise).
Attempted Solutions:
Using Middleware like below:
middleware({ store, params }) {
return store.dispatch('myModule/fetchLocation', params.id)
}
Using asyncData like below:
data(){
return{
filteredLocation: {}
}
}
// snip
async asyncData({ store, params }) {
const { data } = await store.dispatch('myModule/fetchLocation', params.id)
return filteredLocation = data
}
I tried looking into fetch, but apparently you no longer have access to context
Example Code:
In one of my store modules:
/* global google */
import Vue from 'vue'
import * as VueGoogleMaps from '~/node_modules/vue2-google-maps/src/main'
Vue.use(VueGoogleMaps, {
load: {
key: process.env.VUE_APP_GMAP_KEY,
libraries: 'geometry,drawing,places'
}
})
export const state = () => ({
selectedLocation: {}
})
export const actions = {
fetchLocation({ commit }, params) {
return new Promise((resolve) => {
Vue.$gmapApiPromiseLazy().then(() => {
const request = {
placeId: params,
fields: [
'name',
'rating',
'formatted_phone_number',
'geometry',
'place_id',
'website',
'review',
'user_ratings_total',
'photo',
'vicinity',
'price_level'
]
}
const service = new google.maps.places.PlacesService(
document.createElement('div')
)
service.getDetails(request, function(place, status) {
if (status === 'OK') {
commit('SET_PLACE', place)
resolve()
}
})
})
})
}
}
export const mutations = {
SET_PLACE: (state, selection) => {
state.selectedInstructor = selection
}
}
EDIT: I already have it in a plugin named google-maps.js and in my nuxt.config.js file I have:
plugins: [
{ src: '~/plugins/google-maps.js' }
]
//
//
build: {
transpile: [/^vue2-google-maps.js($|\/)/],
extend(config, ctx) {}
}
Using Middleware is how we can access Vuex before page loads. try putting the configuration part in a custom Nuxt plugin.
Create a file in Plugins folder (you can name it global.js).
Put this
import Vue from 'vue'
import * as VueGoogleMaps from '~/node_modules/vue2-google-maps/src/main'
Vue.use(VueGoogleMaps, {
load: {
key: process.env.VUE_APP_GMAP_KEY,
libraries: 'geometry,drawing,places'
}
})
in global.js.
Then add the plugin in nuxt.config.js like this.
plugins: [
'~/plugins/global.js'
]
Also, make sure you're using underscore before 'page_id' name in your folder structure.

Vuejs getting data from local json

I got some json data in a local file the file is .txt file and the data is not directly accessible so I just changed the file format to .json and after that, I tried to get clean data to loop through with the code below.
I'm getting the data via computed in this component but I want to set this clean data as a prop to a child component.
I want to create many child components with clean data.
Thank you very much in advance!
Code:
<script>
export default {
name: 'Dashboard',
components : {
'my-table': mytable,
'my-search': search,
},
data: function() {
return {
casesDataList: [],
};
},
computed:{
ClearList: function(){
var casesDataList = this.casesDataList.map(function (neo){
return {ID: neo.Attributes[1].Value, Date: neo.FormattedValues[0].Value, Owner: neo.FormattedValues[1].Value};
});
return casesDataList;
}
},
created: function(){
this.getCasesData();
},
methods: {
getCasesData() {
fetch("Weather.json")
.then(response => response.json())
.then(data => (this.casesDataList = data.Entities));
},
}
};
</script>
You can pass the computed as a prop to the child directly:
<child :propname="ClearList"></child>
In the child:
export default {
props: ['propname'],
// ...
}

Calling a local json file and parsing data in ReactJS

I have the following json file. Right now, i have kept this in my ReactJS project itself locally. Later on planning to move in a server location.
abtestconfig.json
[
{
"abtestname": "expAButton",
"traffic": 1,
"slices":
[
"orange",
"blue"
]
},
{
"abtestname": "expTextArea",
"traffic": 0.5,
"slices":
[
"lightgrey",
"yellow"
]
}
]
I want to read and get data and parse it and apply in a function. I got some reference sample code and trying to use fetch api to react json file with the following code.
After reading this json file, i will have to pass the data in abtest function, as you can see now it's sending with hard coded value abtest('expAButton', 0.75).slices('orange', 'blue').run(function ()
I have the following doubts and wanted to get your guidance / clarification.
1. Is it correct way to read json file using fetch api? Is there any other best approach?
2. When I use fetch api like mentioned below, console log displays GET http://localhost:8080/abtesting/abtestconfig.json 404 (Not Found)
app.jsx file:
import './abtesting/abtestconfig.json';
class App extends React.Component {
constructor() {
super();
this.onClick = this.handleClick.bind(this);
this.onClickNewUser = this.handleNewUser.bind(this);
this.state = {
bgColor: '',
data: []
}
};
handleNewUser (event) {
abtest.clear();
window.location.reload();
}
render() {
return (
<Helmet
/>
<p><b>A/B Testing Experience</b></p>
<div className="DottedBox">
<p><button id = "newUserButton" onClick = {this.onClickNewUser} style={{backgroundColor:"red"}}>Welcome and click here</button></p>
</div>
);
}
handleClick () {
abtest('expAButton', 0.75).slices('orange', 'blue').run(function () {
expAButton.style.backgroundColor = this.slice.name;
});
}
setStyle (stylecolor) {
this.setState({
bgColor: stylecolor
})
}
componentDidMount () {
this.handleClick();
fetch('./abtesting/abtestconfig.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
}
}
export default hot(module)(App);

How to display image returned in JSON response after uploading

I have a page where you can upload images. Everything works except I don't know how to make the page refresh with the new image which is returned in the json response on success. I cant use location.reload() because it refreshes the whole app and starts off from the home page. I am using angular2/typescript for my frontend
component.ts (The image value is returned on success)
uploadFile(): any {
let file = this.fileInput.nativeElement;
if (file.files && file.files[0]) {
let fileToUpload = file.files[0];
this.getService
.uploadImg(fileToUpload)
.subscribe(
response => {
},
err => {
console.log("ERR", err)
}
},
() => console.log("Success")
);
}
My solution would be to update the src attribute of the img container. This can be done using the setAttribute function. A primitive example is below.
Javascript
uploadFile(): any {
let file = this.fileInput.nativeElement;
if (file.files && file.files[0]) {
let fileToUpload = file.files[0];
this.getService
.uploadImage(fileToUpload, this.id)
.subscribe(
response => {
this.image = response.image;
document.getElementbyId("image-id").setAttribute("src", "data:image/JPG;base64," + pic.pic );
},
err => {
console.log("ERR", err)
}
},
() => console.log("Success")
);
}
HTML
<div *ngIf="pic.pic">
<img id="image-id" [src]="'data:image/JPG;base64,' + pic.pic" />
</div>
Heres how I solved it.
component.ts (The image value is returned on success)
pic: any;
upload: any {
let file = this.fileInput.nativeElement;
if (file.files && file.files[0]) {
let fileToUpload = file.files[0];
this.getService
.uploadImg(fileToUpload)
.subscribe(
response => {
//Assign the response here
this.pic = response.image;
},
err => {
console.log("ERR", err)
}
},
() => console.log("Success")
);
}
The html page
<img [src]="'data:image/JPG;base64,' + pic " />

How to modify json data in after storing in vue data object

This is my vue code :
new Vue({
el : '#root',
data : {
blog : []
},
created() {
this.$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
// console.log(response.data)
this.blog = response.data
})
.catch(function (error) {
this.error = 'Error! Could not reach the API. ' + error
})
}
});
My html code is :
<div id="root" class="container">
<ul v-for="post in blog">
<li> {{ post.id }} </li>
<li>{{ post.userId }} </li>
<li>{{ post.title }} </li>
</ul>
</div>
Now I can show every user's name just fine, but I want to modify something like if user id is 1 then the user's name will be changed into "Smith".
I tried this code:
mounted() {
if (this.blog[0].userId == 1) {
this.blog[0].userId = 'Smith'
}
}
But it shows this error :
Uncaught TypeError: Cannot read property 'userId' of undefined
If I used in method with event it works just fine! How to do this ?
After console.log(this.blog)
Also after console.log(this.blog[0].userId) I get : "1"
Problem is that your code in mounted() method done before you push response.data in blog array. So that's why it can't read any of properties.
You can call methods after you fetch data, in then() callback to be sure that you have data in blog array and then call methods for working with a blog:
new Vue({
el: "#vue",
data() {
return {
blog: []
};
},
methods: {
changeNames() {
if (this.blog[0].userId == 1) {
this.blog[0].userId = "Smith";
}
}
},
created() {
Vue.http
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
this.blog = response.data;
this.changeNames();
})
.catch((error) => {
this.error = "Error! Could not reach the API. " + error;
});
}
});
Here is working example: jsFiddle