Vuejs getting data from local json - 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'],
// ...
}

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.

Cypress fixtures structure json and type

i have one form with two inputs
context('Include contains from json file', function () {
beforeEach(() => {
cy.server()
cy.fixture("example.json")
.as('data')
.then((data) => {
cy.route('GET', 'example.json', data)
})
})
it('Výběr klienta', function () {
cy.visit('/info')
cy.get('[data-cy=username]').type(JSON.stringify(this.data)
cy.get('[data-cy=surname]').type(JSON.stringify(this.data)
})
})
How to type contains for two or more inputs from external file .json
My .json file
{
"name": "Jane"
"surname": "Doe"
}
The .json file should be in the fixtures folder as cypress will automatically search for test data inside this folder by default until and unless the path is specified otherwise.
You have to load the fixtures file in your tests in beforeEach() cy.fixture('example.json').as('data')
Then your code would be:
cy.get('[data-cy=username]').type(data.name)
cy.get('[data-cy=surname]').type(data.surname)
Works for me perfectly in single fixture JSON with multiple data and not stub API
before describe('Test Single Input Field Form', function() declare :
const testData = require("../../fixtures/multipleInputFields.json")
and then
`testData.forEach((data) => {
const message = data.message
it('Test Case', function(){
cy.log("data is:" + data)
cy.get('#user-message').type(message).should('have.value', message)
cy.get('#get-input > button').click()
cy.wait(200)
cy.get('span#display').should('have.text', message)
})
});`

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);

It Shows value as undefined in webpage when i enter value from JSON file, Any idea?

It Shows value as undefined in webpage when i enter value from JSON file, Any idea?
JSON FILE:
[
{
"firstName":"1233232322",
"lastName":"ramakrishnan",
"email":"parthiramkrish#gmail.com",
"password":"secondmay1991",
"confirmPassword":"secondmay1991"
}
]
SPEC FILE:
'use strict';
browser.ignoreSynchronization = true;
var testdata1 = require('./testdata1.json');
describe("Test the inksoft.com create an account page", function () {
it("enter the account details", function () {
browser.get("https://qa.inksoft.com/EGT");
browser.ignoreSynchronization = true;
browser.sleep(15000);
element(by.xpath("//a[text()='Create Account']")).click();
browser.sleep(20000);
element(by.xpath("//input[#name='firstName']")).sendKeys( testdata1.firstName);
element(by.xpath("//input[#name='lastName']")).sendKeys( testdata1.lastName);
element(by.xpath("//input[#name='email']")).sendKeys( testdata1.email);
element(by.xpath("//input[#name='password']")).sendKeys( testdata1.password);
element(by.xpath("//input[#name='confirmPassword']")).sendKeys( testdata1.confirmassword);
element(by.xpath("//input[#type='submit']")).click();
});
});
CONF FILE:
exports.config = {
//The address of a running selenium server.
seleniumAddress: 'http://localhost:4444/wd/hub',
//Here we specify the name of the specs files.
framework: 'jasmine',
specs: ['inksoftdata.js'],
jasmineNodeOpts: {
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 1440000
},
}
In testdata1.json file, all the data are stored as an array of objects. So to access the data from testdata1 variable you need to specify the array index like testdata1[0].firstName.

Load JSON data directly into highcharts angular

I am using https://github.com/pablojim/highcharts-ng to build Highcharts in my angularjs app. As suggested on that site I am configuring my chart configs in my controller as follows:
$scope.chartConfig6 = {
options: {
chart: {
type: 'bar'
}
},
series: [{
data: [33, 55, 10, 18, 17]
}],
title: {
text: 'Agent FNOL Ranking'
},
loading: false
}
Now I have a json file: http://pastebin.com/SEu8dHkB if you do a search you can find the field called "highChart" on the json which contains the configurations for a highchart. Now I want to be able to use these configurations directly from the json to to my highcharts config either in the controller or as a directive. This is how I get the json file via http in my service:
.factory('Swoop',function($http,$filter,$q){
return {
all: function(){
var deferred = $q.defer();
$http.get("swoop.json").success(
function(data){
// angular.copy(data, studies);
deferred.resolve(data);
}
);
return deferred.promise;
}
}})
However, I am not sure how I could render this data(under the highChart object in the json) to the $scope.chartConfig6 like I did above. Can someone please show me how this could be done?