In my Navigation I want to insert Links from my CMS. I am using Axios. My Navigation is Vue. How do I get the data from the JSON file into the const?
Just knowing if I need to search for the solution in Axios or in Vue would help alot too.
import axios from "axios";
const exhibitions = [
{
name: "Exhibition 1",
description: "Info 1",
href: "#",
},
{
name: "Exhibition 2",
description: "Info 2",
href: "#",
},
];
my export default:
export default {
name: "item",
data() {
return {
info: null,
};
},
mounted() {
axios
.get("http://localhost:8000/posts.json")
.then((response) => (this.info = response));
},
posts.json
{
"data":
[{
"id":1028,
"title":"Exhibition 1",
"slug":"exhibition-2009",
"url":"http://localhost:8000/exhibitions/exhibition-2009"
},
{
"id":905,
"title":"Exhibition 2",
"slug":"exhibition-2006",
"url":"http://localhost:8000/exhibitions/exhibition-2006"
}],
"meta":
{
"pagination":
{
"total":2,
"count":2,
"per_page":100,
"current_page":1,
"total_pages":1,
"links":{}
}
}
}
What do you mean by "Get the data from the JSON into the const"??
Just a reminder, a constant cannot be modified.
According to what you commented, I guess that you'd like to store the data fetched from your json file to info variable. And then, render your links in the navigation bar.
mounted() {
axios
.get("http://localhost:8000/posts.json")
.then((response) => (this.info = response));
}
Once the component is mounted you're fetching your JSON data from the file using Axios. When the promise is accepted then you store the response data to this.info. Once you have your data in that variable you can render everything ⬇️
There's a directive in VueJS for list rendering called v-for. You can use it to render all the links to your navigation bar.
<ul id="navigation-bar">
<li v-for="i in info">
{{ i.title }}
</li>
</ul>
Related
I'm using next.js and I want to fetch data from my data1.json file via getStaticProps(). The problem is that I get the error:
FetchError: invalid json response body at http://localhost:3000/data/data1.json reason: Unexpected token < in JSON at position 0
I have following code:
trainings.js (projectfolder/pages/trainings.js)
export default function Trainings({ data }) {
console.log(data);
return (
<main>
<h1>My trainings</h1>
</main>
);
}
export async function getServerSideProps() {
const res = await fetch('http://localhost:3000/data/data1.json');
const data = await res.json();
return { props: { data } };
}
data1.json (projectfolder/data/data1.json)
[
{
"name": "Jescie Duncan",
"email": "nunc#protonmail.couk",
"address": "Ap #666-9989 Nisi Avenue"
},
{
"name": "Karen Bartlett",
"email": "tellus.imperdiet#aol.couk",
"address": "P.O. Box 787, 2857 Tincidunt Ave"
},
{
"name": "Teegan Valdez",
"email": "lacus.mauris.non#hotmail.edu",
"address": "Ap #474-300 Nullam Avenue"
},
{
"name": "Stuart Silva",
"email": "nulla.donec.non#google.edu",
"address": "336-2367 Eu Ave"
}
]
Please check whether http://localhost:3000/data/data1.json api is working or not. Because Nextjs support React components as default support in the pages folder not JSON. If you want serve as API you need to use NextJS api routes which you need to specifically put logic inside api folder.
in api/data/data1.js file
import data from '/path/to/json'
async function handler(req, res) {
return res.status(200).json(data)
}
export default handler;
But a better approach is:
As you have JSON file, you directly import that data in trainings.js rather than calling an API.
import data from 'path/to/json';
export async function getServerSideProps() {
return { props: { data } };
}
Trying to load the comments from my local json file but can't seem to get it to load properly. It's currently just showing a bulleted list of "0, 1, 2". Any ideas?
import React, { Component } from 'react'
import data from './../data'
class CommentList extends Component {
render () {
const elem = data.comments;
return (
<ul>
{Object.keys(elem).map(s => (<li>{s}</li>))}
</ul>
)
}
};
export default CommentList
{
"comments": [
{
"text": "Australian Shepherd!"
},
{
"text": "German Shepherd!"
},
{
"text": "Mutts all the way"
}
]
}
elem is an array so don't need Object.keys:
{elem.map(s => (<li>{s.text}</li>))}
I've been trying to change inline data (which worked) to external data in a JSON file.
Originally, I had this, which worked:
const treeData = [
{
name: "Parent"
attributes: {
id: 12345678
},
children: [
{
name: "Child"
attributes: {
id: 12345679
},
}
]
}
]
return(
<Tree data = {treeData}/>
)
So now I have an external JSON file that looks like this:
{
"name": "Parent",
"attributes": {
"id": 12345678,
},
"children": [
{
"name": "Child",
"attributes": {
"id": 12345679,
}
}
]
}
]
And in my program:
const[treeData, setTreeData] = useState(undefined)
const jsonSource = '../../data/tree-data.json'
/* Used to center the tree on render */
useEffect(()=> {
// Some irrelevant code here...
// Parse JSON data (Relevant)
return function parseJSONFile(){
treeUtil.parseJSON(jsonSource).
then((data) => setTreeData({data}))
.catch((error)=>console.log(error))
}
}, []);
return(
<Tree data = {treeData} />
)
Aand it does not work. Error message:
TypeError: Cannot set property 'id' of undefined
Which makes me confused because it's my first time dealing with JSON. Any insight on this can help!
You can do it in a very simple way (No need for extra works you are doing):
import treeData from "./tree-data.json"; // Import your json file (Path to your json file)
function App() {
return <Tree data={treeData} />;
}
Your code have many problems including you write your parseJSONFile in return of useEffect, Also you just defined parseJSONFile and you are not calling it, and even you call, it will be executed on component unmount (because you call it on return of useEffect), Also initial state of your treeData is undefined and it's the cause of TypeError: Cannot set property 'id' of undefined.
My codesandbox link (https://codesandbox.io/s/react-hooks-counter-demo-dh0q4?file=/src/index.js).
I'm trying to implement a decoupled wordpress solution and I'm having a bit of confusion displaying the JSON object properties in my template. I'm able to return JSON objects for the WP API but not sure how to handle them. The only way I can get a property to display it's value in a template is if I add a [0] to the interpolated property, which won't work in an ngFor loop. I've read the solution by #Thierry here access key and value of object using *ngFor
but this doesn't seem to be how Google handles the Tour of Heroes app http://plnkr.co/edit/WkY2YE54ShYZfzJLSkMX?p=preview
Google uses this data set:
{
"data": [
{ "id": "1", "name": "Windstorm" },
{ "id": "2", "name": "Bombasto" },
{ "id": "3", "name": "Magneta" },
{ "id": "4", "name": "Tornado" }
]
}
which looks like a JSON object to me, so how is the app able to handle something like this:
<ul>
<li *ngFor="let hero of heroes">
{{hero.name}}
</li>
</ul>
I'm just unclear if there's been a change in RC5 that allows iteration over an object, or do I still need to transform this somehow. I'm very new to Angular and could use a little guidance on this matter. Thanks!!
An update based on the comments, if I want to transform an api request like http://localhost:8888/wp-json/wp/v2/posts, what's the best method for that? My return code would look something like:
[
{
"id": 4,
"date": "2016-08-09T00:09:55",
"date_gmt": "2016-08-09T00:09:55",
"guid": {
"rendered": “http://localhost:8888/?p=4"
},
"modified": "2016-08-09T00:11:05",
"modified_gmt": "2016-08-09T00:11:05",
"slug": “wp-api-test”,
"type": "post",
"link": "http://localhost:8888/2016/08/wp-api-test”,
"title": {
"rendered": "testing the wp api"
},
"content": {
"rendered": "<p>loreum ipsum</p>\n"
},
"excerpt": {
"rendered": "<p>loreum ipsum</p>\n"
},
"author": 1,
"featured_media": 0,
"comment_status": "open",
"ping_status": "open",
"sticky": false,
"format": "standard",
"categories": [
1
],
}
]
Without writing all the code for you, there is no short answer to what you are asking, but here are some tips:
You have to take the JSON response you are getting back and create either an interface or class in TypeScript so when you perform the POST, Angular 2 can take the JSON and convert it to an object using your classes.
JSON to TS generator: http://json2ts.com/
Ninja Tips 2 - Make your JSON typed with TypeScript - http://blog.ninja-squad.com/2016/03/15/ninja-tips-2-type-your-json-with-typescript/
TypeScript Json Mapper - http://cloudmark.github.io/Json-Mapping/
How are you defining your services?
Here's an example:
export interface IPost {
id: number;
date: Date;
date_gmt: Date;
... // rest of your defintion
}
#Injectable()
export class BlogPostService {
private http: Http;
constructor(http: Http) {
this.http = http;
}
private apiUrl: string = 'api/blog/posts.json';
getPosts(): Observable<IPost[]> {
return (this.http.get(this.apiUrl)
.map((response: Response) => <IPost[]>response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError)) as any;
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || "Server error");
}
}
This line should transform your json object to array[] of IPosts
.map((response: Response) => <IPost[]>response.json())
Hope that helps.
Thanks so much for the answers. They helped lead me to the solution. I was able to solve this rather simply by creating a posts array and making it equal to the Observable return. The component looks like this:
posts: {};
constructor (private _wpService: WpApiService) {}
ngOnInit() { this.getPosts() }
getPosts() {
this._wpService.getPosts()
.subscribe(
data => {
this.posts = data;
});
}
The template looks like:
<li *ngFor="let post of posts">
<h3>{{post.title.rendered}}</h3>
</li>
Just replace {{hero.name}} by {{hero.data.name}}
The best way to handle the JSON object by creating an interface class to access the data easily
making first attempt to master Ember.js atm. I'm trying to make a simple CMS, but for some reason I have a problem with getting any data from json displayed. I've already switched from Fixture to RESTAdapter, but I am still stuck with
Error: assertion failed: Your server returned a hash with the key timestamp but you have no mapping for it.
Here's my js code:
App.Store = DS.Store.extend(
{
revision:12,
adapter: 'DS.RESTAdapter'
}
);
App.Menucategory = DS.Model.extend({
timestamp: DS.attr('number'),
status: DS.attr('string')
});
App.MenucategoryRoute = Ember.Route.extend({
model: function() {
return App.Menucategory.find();
}
});
DS.RESTAdapter.reopen({
url: <my url>
});
DS.RESTAdapter.configure("plurals", {
menucategory: "menucategory"
});
Trying to access it with:
<script type="text/x-handlebars" id="menucategory">
{{#each model}}
{{data}}
{{/each}}
</script>
My json structure:
{
"timestamp": 1366106783,
"status": "OK",
"data": [
{
"name": "starters",
"id": 1
},
{
"name": "main dishes",
"id": 2
}]}
Thank you in advance for any help you can provide.
By default the RESTAdapter expects your API to be in a specific format, which your API doesn't conform to, if you can modify your API, you need to get it to return in this format, otherwise you'll need to customize the adapter.
Expected Format (based on your JSON):
{
"menucategory": [
{
"name": "starters",
"id": 1
},
{
"name": "main dishes",
"id": 2
}
],
"meta": {
"timestamp": 1366106783,
"status": "OK",
}
}