I've been trying to import a local JSON file into my react components state for a while now and no matter how much i google and try - i cant seem to get it to work. Here is my json file:
{
"products": [
{"id": 1, "category": "paint", "name": "clowd", "type": "matt emulsion", "stocked": true, "size": "100x130", "thumbnail": "23-sm.png", "previewImg": "23.png"},
{"id": 2, "category": "paint", "name": "dålig sikt", "type": "matt emulsion/olja/akryl", "stocked": true, "size": "100x130", "thumbnail": "24-sm.png", "previewImg": "24.png"},
{"id": 25, "category": "print", "name": "MIMI | 2nd edition", "type": "akvarellppr, 70x100", "limited": "30", "available": "28", "price": "3,000", "stocked": true, "thumbnail": "mimisecond-sm.jpg", "previewImg": "mimisecond.jpg"},
{"id": 26, "category": "print", "name": "max", "type": "uppspänd canvas, 95x120", "limited": "30", "available": "28", "price": "7,000", "stocked": true, "thumbnail": "max-sm.jpg", "previewImg": "max.jpg"},
{"id": 38, "category": "places", "stocked": true, "desc": "Vernisage Strössel # Linnégatan, sthlm 2015", "thumbnail": "17.png", "previewImg": "17.png"},
{"id": 39, "category": "places", "stocked": true, "desc": "Max # Nybergsgatan, sthlm 2016", "thumbnail": "26.png", "previewImg": "26.png"}
]
}
Here is my react component:
import React, { Component } from 'react';
import data from 'data.json';
console.log(data);
// Component import
import Menu from './components/menu';
import Footer from './components/footer';
import ProductContainer from './components/productContainer';
import CategoryContainer from './components/categoryContainer';
class Archive extends React.Component {
constructor(props){
super(props);
this.state = {
products: data,
category: ""
};
this.filterHandler = this.filterHandler.bind(this);
}
// Set component state to the currently clicked "cat" (CategoryItem)
filterHandler(tag){
this.setState({
category: tag
})
}
render() {
// 1. Render CategoryContainer with props products and filterHandler function to show all uniqe CategoryItems and filter products based on category
// 2. Render ProductContainer based on category. If this.state.category.length is true - filter "prod" & where prod.categories is same type and name as this.state.category : else render all this.state.categories that matches "paint".
return (
<div>
<Menu />
<div className="archive-container">
<div className="archive-wrapper">
<CategoryContainer
filterHandler={this.filterHandler}
products={this.state.products}
/>
<br/><br/>
<ProductContainer
products={this.state.category.length
? this.state.products.filter((prod) => prod.category === this.state.category)
: this.state.products.filter((prod) => prod.category === 'paint')
}
/>
</div>
</div>
<Footer />
</div>
);
};
};
export default Archive;
Here is my webpack2 file:
// DEVELOPMENT
const webpack = require('webpack');
const path = require('path');
const entry = [
'webpack-dev-server/client?http://localhost:8080', // bundle the client for webpack-dev-server and connect to the provided endpoint
'webpack/hot/only-dev-server', // bundle the client for hot reloading only- means to only hot reload for successful updates
'./app.js'
]
const output = {
path: path.join(__dirname, 'dist'),
publicPath: '/dist',
filename: 'bundle.min.js'
}
const plugins = [
new webpack.HotModuleReplacementPlugin(), // enable HMR globally
new webpack.NamedModulesPlugin() // prints more readable module names in the browser console on HMR updates
]
const config = {
context: path.join(__dirname, 'src'),
entry: entry,
output: output,
devtool: "inline-source-map",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
use: {
loader: "babel-loader"
}
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'url-loader',
options: { limit: 10000, name: './images/[name].[ext]' }
}]
},
{
test: /\.(sass|scss)$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}
]
},
plugins: plugins,
externals: {
jquery: 'jQuery'
}
}
module.exports = config
I get the error:
If I change the json file to a javascript object and input it directly into the constructor:
constructor(props){
super(props);
this.state = {
products: [
{id: 1, category: 'paint', name: 'clowd', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '23-sm.png', previewImg: "23.png"},
{id: 2, category: 'paint', name: 'dålig sikt', type: 'matt emulsion/olja/akryl', stocked: true, size: '100x130', thumbnail: '24-sm.png', previewImg: "24.png"},
{id: 3, category: 'paint', name: 'dålig sikt', type: 'matt emulsion/olja/akryl', stocked: true, size: '100x130', thumbnail: '25-sm.png', previewImg: "25.png"},
{id: 4, category: 'paint', name: 'pink', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '1-sm.png', previewImg: "1.png"},
{id: 5, category: 'paint', name: 'pink', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '27-sm.png', previewImg: "27.png"},
{id: 6, category: 'paint', name: 'pinks', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '2-sm.png', previewImg: "2.png"}
],
category: ""
}
this.filterHandler = this.filterHandler.bind(this);
}
Then it works fine. But I want it in a separate json file so it wont be bundled and so it will be easier for client to add items to the list.
Maybe there is a smarter way to do this, I'm new to react and webpack and are hoping to learn .. Greatful for any form of input. Thank you!
(if someone came to fix this... in comments of question are fixes to common mistakes while importing json file in webpack 2)
Your Archive.state looks like:
{
products: { products: [ (your rest of array) ] },
category: ""
}
Your error is
this.state = {
products: data,
category: ""
};
Should be:
this.state = {
products: data.products,
category: ""
};
Related
We are creating a new version our API (v2) adopting the JSON:API specification (https://jsonapi.org/). I'm not being able to port the ExtJS model associations (belongs_to) to the new pattern.
The ExtJS documentation only shows how to use a nested relation in the same root node (https://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.association.Association).
v1 data (sample):
{
"data": [
{
"id": 1,
"description": "Software Development",
"area_id": 1,
"area": {
"id": 1,
"code": "01",
"description": "Headquarters"
}
},
],
"meta": {
"success": true,
"count": 1
}
}
v2 data (sample):
{
"data": [
{
"id": "1",
"type": "maint_service_nature",
"attributes": {
"id": 1,
"description": "Software Development",
"area_id": 1
},
"relationships": {
"area": {
"data": {
"id": "1",
"type": "area"
}
}
}
}
],
"included": [
{
"id": "1",
"type": "area",
"attributes": {
"id": 1,
"code": "01",
"description": "Headquarters"
}
}
],
"meta": {
"success": true,
"count": 1
}
}
My model:
Ext.define('Suite.model.MaintServiceNature', {
extend: 'Ext.data.Model',
fields: [
{ desc: "Id", name: 'id', type: 'int', useNull: true },
{ desc: "Area", name: 'area_id', type: 'int', useNull: true },
{ desc: "Description", name: 'description', type: 'string', useNull: true, tableIdentification: true }
],
associations: [
{
type: 'belongsTo',
model: 'Suite.model.Area',
foreignKey: 'area_id',
associationKey: 'area',
instanceName: 'Area',
getterName: 'getArea',
setterName: 'setArea',
reader: {
type: 'json',
root: false
}
}
],
proxy: {
type: 'rest',
url: App.getConf('restBaseUrlV2') + '/maint_service_natures',
reader: {
type: 'json',
root: 'data',
record: 'attributes',
totalProperty: 'meta.count',
successProperty: 'meta.success',
messageProperty: 'meta.errors'
}
}
});
Any ideias on how to setup the association to work with the v2 data?
I'm honestly taking a stab at this one... I haven't used Ext JS 4 in years, and I wouldn't structure my JSON like JSON:API does, but I think the only way you can accomplish this is by rolling your own reader class. Given that you have generic properties for your data structure, this reader should work for all scenarios... although, I'm not too familiar with JSON:API, so I could be totally wrong. Either way, this is what I've come up with.
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.myReader',
root: 'data',
totalProperty: 'meta.count',
successProperty: 'meta.success',
messageProperty: 'meta.errors',
/**
* #override
*/
extractData: function (root) {
var me = this,
ModelClass = me.model,
length = root.length,
records = new Array(length),
dataConverter,
convertedValues, node, record, i;
for (i = 0; i < length; i++) {
node = root[i];
var attrs = node.attributes;
if (node.isModel) {
// If we're given a model instance in the data, just push it on
// without doing any conversion
records[i] = node;
} else {
// Create a record with an empty data object.
// Populate that data object by extracting and converting field values from raw data.
// Must pass the ID to use because we pass no data for the constructor to pluck an ID from
records[i] = record = new ModelClass(undefined, me.getId(attrs), attrs, convertedValues = {});
// If the server did not include an id in the response data, the Model constructor will mark the record as phantom.
// We need to set phantom to false here because records created from a server response using a reader by definition are not phantom records.
record.phantom = false;
// Use generated function to extract all fields at once
me.convertRecordData(convertedValues, attrs, record, me.applyDefaults);
if (me.implicitIncludes && record.associations.length) {
me.readAssociated(record, node);
}
}
}
return records;
}
});
Ext.define('Suite.model.Area', {
extend: 'Ext.data.Model',
fields: [{
name: 'type',
type: 'string'
}]
});
Ext.define('Suite.model.MaintServiceNature', {
extend: 'Ext.data.Model',
fields: [{
desc: "Id",
name: 'id',
type: 'int',
useNull: true
}, {
desc: "Area",
name: 'area_id',
type: 'int',
useNull: true
}, {
desc: "Description",
name: 'description',
type: 'string',
useNull: true,
tableIdentification: true
}],
associations: [{
type: 'belongsTo',
model: 'Suite.model.Area',
associatedName: 'Area',
foreignKey: 'area_id',
associationKey: 'relationships.area.data',
instanceName: 'Area',
getterName: 'getArea',
setterName: 'setArea'
}],
proxy: {
type: 'rest',
url: 'data1.json',
reader: {
type: 'myReader'
}
}
});
Suite.model.MaintServiceNature.load(null, {
callback: function (record) {
console.log(record.getData(true));
}
});
}
});
I'm trying to normalize some non conventional json data from server to be used in ember.
The json response looks like this
{
"pagingAndSorting": {
"pageSize": 2,
"ascending": false,
"pageNumber": 5
},
"list": [
{
"recommendedDosage": "400mg Tablets",
"active": true,
"name": "ANT-Norfloxacin",
"id": "FE102EDA-984A-41A3-B9C8-3E13B98A864A",
"identifiers": []
},
{
"recommendedDosage": "",
"active": true,
"name": "ANT-Penicillin Injection",
"id": "F8DE6184-0F91-4DA9-A611-2B78F4B85D25",
"identifiers": []
},
{
"recommendedDosage": "",
"active": true,
"name": "ANT-Spectinomycin",
"id": "73205995-0CF2-4744-A856-F74B81355661",
"identifiers": []
}],
"fullListSize": 574
}
I created the following models
in app/model/paging-and-sorting.js
import DS from 'ember-data';
export default DS.Model.extend({
pageNumber : DS.attr('number',{defaultValue: 0}),
pageSize : DS.attr('number',{defaultValue: 40}),
ascending : DS.attr('boolean', {defaultValue: false})
});
in app/models/medicine.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('String'),
identifiers: DS.attr(''),
active: DS.attr('Boolean',{defaultValue: true}),
id: DS.attr('String'),
recommendedDosage : DS.attr('String')
});
In app/models/medicine-list.js
import DS from 'ember-data';
export default DS.Model.extend({
pagingAndSorting: DS.belongsTo('paging-and-sorting'),
list: DS.hasMany('medicine'),
fullListSize: DS.attr('number')
});
In app/serializers/medicine-list.js i have
import DS from 'ember-data';
//For the embedded Ember model
export default DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
pagingAndSorting : { embedded: 'always' },
list: { embedded: 'always' }
}
});
But this does not seem to be working. I'm not seeing any error in the console, however when i inspect using ember data it seems like no data gets into the ember store.
Am i missing something obvious?
Does anyone have another solution/approach?
Thanks for your help!
i have a json in the following format:
{
"collection": [
{
"id": 4,
"tickets": [
{
"price": 40,
},
{
"price": 50,
}
],
},
{
"id": 1,
"tickets": [
{
"price": 10,
},
{
"price": 15,
}
]
},
]
}
STORE:
Ext.define("myProject.store.ABCs", {
extend: "Ext.data.Store",
config: {
model: "myProject.model.ABC",
autoLoad: false,
proxy: {
type: "ajax",
url: '', //myURL
reader: {
type: "json",
rootProperty: "collection", // this is the first collection
},
},
}
});
For this particular JSON i created the models as:
Ext.define("myProject.model.ABC", {
extend: "Ext.data.Model",
config: {
idProperty: "id",
fields:[
{name: "id", type: "int" },
],
hasMany: [
{
model: "myProject.model.XYZ",
name: "tickets",
associationKey: "tickets",
},
],
}
});
And second model as:
Ext.define("myProject.model.XYZ", {
extend: "Ext.data.Model",
config: {
// idProperty: "id",
fields:[
{name: "inner_id", type: "int" },
],
belongsTo: 'myProject.model.ABC'
}
});
This particular code creates a store and populates the models correctly.
var store = Ext.getStore('ABCs');
Now i want to sort this store based on store.tickets().getAt(0).get('price') that is sort the ABC records based on XYZ's first price property.
In the above json. ABC Records will be: [{id:4}, {id:1}]
But since first price in XYZ (40 > 10), i want to sort them and create [{id:1}, {id:4}]
Take a look at the Ext.util.Sorter class, where you can set a sorterFn. See the example at the top of the page - you should be able to simply write the logic for sorting records the way you describe.
I've started creating a Sencha Touch 2 app that has two models defined, Change and Configuration. A Change belongsTo a Configuration. Both of the models also have a store setup. On the Changes store I have a proxy setup to request data that comes back in JSON format. The JSON data has a Change with a nested configuration. The Change loads just fine but when I try and get the associated Configuration from the Change instance it isn't working.
I've defined the models like this:
Change model:
Ext.define('Changes.model.Change', {
extend: 'Ext.data.Model',
xtype: 'changemodel',
config: {
fields: [
{name:'id', type:'int'},
{name:'changeId', type:'string'},
{name:'briefDescription', type:'string'},
{name:'configuration_id', type:'int'}
],
associations: [{
type:'belongsTo',
model:'Changes.model.Configuration',
primaryKey: 'id',
foreignKey: 'configuration_id',
associationKey: 'configurations'
}],
},
});
Configuration Model:
Ext.define('Changes.model.Configuration', {
extend: 'Ext.data.Model',
xtype: 'configurationmodel',
config: {
fields: [
{ name: 'id', type: 'int'},
{ name: 'longName', type: 'string' },
{ name: 'ciName', type: 'string' },
],
hasMany: {model: 'Change', name: 'changes'}
}
});
Each model has a store.
Changes store:
Ext.define('Changes.store.Changes', {
extend: 'Ext.data.Store',
requires: 'Changes.model.Change',
config: {
model: 'Changes.model.Change',
proxy: {
type: 'ajax',
url: 'services/changes.php',
reader: {
type: 'json',
rootProperty: 'changes'
}
},
sorters: [{ property: 'briefDescription', direction: 'ASC'}],
}
});
Configurations store:
Ext.define('Changes.store.Configurations', {
extend: 'Ext.data.Store',
requires: ['Ext.data.proxy.LocalStorage'],
config: {
model: 'Changes.model.Configuration',
grouper: {
sortProperty: "ciName",
direction: "DESC",
groupFn: function (record) {
return record.get('ciName')[0];
}
},
proxy: {
type: 'ajax',
url: 'services/configurationItems.php',
reader: {
type: 'json',
rootProperty: 'configurationItems'
}
}
}
});
My JSON that is being returned from services/changes.php looks like this:
{
"success": true,
"changes": [
{
"id": 1,
"changeId": "XYZ19178263",
"briefDescription": "Loaded from Proxy",
"configuration_id": 3,
"configurations": [
{
"id": "3",
"longName": "999-99_-_windows_7_desktop.Computer.Windows",
"ciName": "999-99_-_windows_7_desktop"
}
]
}
]
}
In the browser's console I can issue the following commands:
Changes.myStore = Ext.getStore('Changes');
Changes.myStore.load();
Changes.record = Changes.myStore.findRecord('id', '1');
Changes.record.getAssociatedData()
The last command will return an object with a Configuration object inside but all of the field values show null except for id which appears to be set to a random value:
Object
Configuration: Object
ciName: null
id: "ext-record-11"
longName: null
Can anyone see why the nested Configuration instance in my JSON isn't being saved? And should the nested Configuration instance in the JSON be added to the Configurations store automatically?
Sadly this just doesn't work. Appears to be a shortcoming of the framework. You can't load and save associated (aggregated/nested) objects. You need to flatten out your structure and then associate objects in code yourself.
So for example... your JSON would then be...
{
"success": true,
"changes": [
{
"id": 1,
"changeId": "XYZ19178263",
"briefDescription": "Loaded from Proxy"
}
]
}
And a second JSON file/response as follows:
{
"success": true,
"configurations": [
{
"id": "3",
"longName": "999-99_-_windows_7_desktop.Computer.Windows",
"ciName": "999-99_-_windows_7_desktop",
"change_id": 1
}
]
}
Tinashe's answer is not correct. You can certainly get nested models.
You have your associations backward with respect to your JSON, however.
"changes": [
{
"id": 1,
"changeId": "XYZ19178263",
"briefDescription": "Loaded from Proxy",
"configuration_id": 3,
"configurations": [
{
"id": "3",
"longName": "999-99_-_windows_7_desktop.Computer.Windows",
"ciName": "999-99_-_windows_7_desktop"
}
]
}
]
means a change hasMany configurations, but you are saying it belongsTo it. This is the correct JSON:
"changes": [
{
"id": 1,
"changeId": "XYZ19178263",
"briefDescription": "Loaded from Proxy",
"configuration_id": 3,
"configuration":
{
"id": "3",
"longName": "999-99_-_windows_7_desktop.Computer.Windows",
"ciName": "999-99_-_windows_7_desktop"
}
}
]
Either way, you need to set getterName (setterName if you like too) on the relationship:
associations: [{
type:'belongsTo',
model:'Changes.model.Configuration',
primaryKey: 'id',
foreignKey: 'configuration_id',
associationKey: 'configuration',
getterName:'getConfiguration'
}]
Then after the store loads, you can call myChangeModel.getConfiguration();
Similar to this question, I can't get my DataView to actually show data. I tried to restructure my store, but I think I'm missing something. Here's what I've got so far:
App, Model, Store
Ext.regApplication({
name: 'TestApp',
launch: function() {
this.viewport = new TestApp.views.Viewport();
}
});
TestApp.models.StoreMe = Ext.regModel('TestApp.models.StoreMe', {
fields: [
'id',
'name',
'age'
]
});
TestApp.stores.storeMe = new Ext.data.Store({
model: 'TestApp.models.StoreMe',
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json'
}
},
autoLoad: true
});
Viewport and DataView
TestApp.views.Viewport = Ext.extend(Ext.Panel, {
fullscreen: true,
layout: 'card',
items: [
{
id: 'dataView',
xtype: 'dataview',
store: TestApp.stores.storeMe,
itemSelector: 'div.dataViewItem',
emptyText: 'NO DATA',
tpl: '<tpl for "."><div class="dataViewItem">ID: {id}<br />Name: {name}<br />Age: {age}</div></tpl>'
}
]
});
JSON
[
{
"id": "1",
"name": "sam",
"age": "4"
},
{
"id": "2",
"name": "jack",
"age": "3"
},
{
"id": "3",
"name": "danny",
"age": "12"
}
]
Any ideas? All of the other questions that are similar to this use Ext.JsonStore, but the Sencha API docs say to do it this way.
UPDATE
The store is working fine. Here's what TestApp.stores.storeMe.data looks like:
Ext.util.MixedCollection
...
items: Array[3]
0: c
data: Object
age: "4"
id: "1"
name: "sam"
1: c
2: c
length: 3
__proto__: Array[0]
keys: Array[3]
length: 3
...
Seems you don't have the json structure with the root called "data"? Try the change your json to:
{
"data": [ {
"id": "1",
"name": "sam",
"age": "4"
}, {
"id": "2",
"name": "jack",
"age": "3"
}, {
"id": "3",
"name": "danny",
"age": "12"
} ]
}
And put a line -- root: 'data' -- in your reader.
I'm an idiot. I had:
tpl: '<tpl for "."><div class="dataViewItem">ID: {id}<br />Name: {name}<br />Age: {age}</div></tpl>'
I needed:
tpl: '<tpl for=".">...</tpl>'