I have this db.json and I want to migrate to file. How do I implement it? I had tried this way above and it didn't work for me. When I put the file in src folder, there appears an error message:
Module not found: Can't resolve 'houses.json' in 'C:\Users\user\Desktop\dir\src'
It does the same thing when I put the file in the public folder.
It is my db.json file:
{ "houses": [
{
"id": 1,
"name": "Title here",
"text": "Text here",
"photos": [
"pic1",
"pic2",
"pic3"
]
},
"houses": [
{
"id": 2,
"name": "Title here",
"text": "Text here",
"photos": [
"pic1",
"pic2",
"pic3"
]
},
"houses": [
{
"id": 3,
"name": "Title here",
"text": "Text here",
"photos": [
"pic1",
"pic2",
"pic3"
]
}
}
I had traded this line
const URL = 'http://localhost:3001/houses';
for this other
const URL = require('houses.json');
And it caused the error message showed before.
And how do I fetch these datas from axios? I was fetching datas from json-server doing this way below. It was successfully. I want to do the same thing but not from json-server but using .json file.
const URL = 'http://localhost:3001/houses';
class House extends Component {
constructor(props) {
super(props);
this.state = {
index: 0,
totalHouses: [],
currentHouse: [],
name: [],
photos: [],
text: []
};
}
componentDidMount() {
axios.get(URL)
.then(res => {
this.setState({
totalHouses: Object.keys(res.data),
currentHouse: res.data
})
})
}
//...rest of the code omitted
Here's a simple example how to achieve what you need, while preserving your state approach.
const houses = require('./houses.json');
class House extends Component {
constructor(props) {
super(props);
this.state = {
index: 0,
totalHouses: [],
currentHouse: [],
name: [],
photos: [],
text: []
};
}
componentDidMount() {
this.setState({
totalHouses: Object.keys(houses.data),
currentHouse: houses.data
})
}
//...
}
You can also achieve it without componentDidMount:
const houses = require('./houses.json');
class House extends Component {
constructor(props) {
super(props);
this.state = {
index: 0,
totalHouses: Object.keys(houses.data),
currentHouse: houses.data
name: [],
photos: [],
text: []
};
}
//...
}
It should be require('./houses.json');. Right now it looks for this file inside node_modules or even higher.
Related
These are the functions that I use for my class component
constructor() {
super();
this.state = {
data: []
}
}
async componentDidMount() {
var citas_data = await makeRequest('api/products/');
citas_data.data.map(data => (
this.setState({
data: [...this.state.data, [{ id: data._id, name: data.name }]]
})
))
}
This is the information contained in the var citas_data, brings it from an api I have in nodejs.
{
"data": [
{
"_id": "600db7499f933921c0a56f95",
"name": "laptop hp 8gb",
"category": "razer",
"price": 80000,
"imgUrl": "https://cnet1.cbsistatic.com/img/P2IudsL7buTCG7zvs4gq5BNpOS4=/470x376/2018/06/27/ba86ad23-6537-4466-b709-e3eaeb662700/11-asus-tuf-gaming-fx504.jpg",
"createdAt": "2021-01-24T18:07:05.811Z",
"updatedAt": "2021-01-24T18:07:22.941Z"
},
{
"_id": "600e39f22ac1a14a10c8ed59",
"name": "laptopa razer",
"category": "raazer",
"price": 99000,
"imgUrl": "https://cnet1.cbsistatic.com/img/P2IudsL7buTCG7zvs4gq5BNpOS4=/470x376/2018/06/27/ba86ad23-6537-4466-b709-e3eaeb662700/11-asus-tuf-gaming-fx504.jpg",
"createdAt": "2021-01-25T03:24:34.776Z",
"updatedAt": "2021-01-25T03:24:34.776Z"
},
{
"_id": "600e3d607e0b6b44d8e98bf8",
"name": "laptopa razer",
"category": "raazer",
"price": 99000,
"imgUrl": "https://cnet1.cbsistatic.com/img/P2IudsL7buTCG7zvs4gq5BNpOS4=/470x376/2018/06/27/ba86ad23-6537-4466-b709-e3eaeb662700/11-asus-tuf-gaming-fx504.jpg",
"createdAt": "2021-01-25T03:39:12.093Z",
"updatedAt": "2021-01-25T03:39:12.093Z"
}
],
"status": 200,
"statusText": "OK",
And when executing the code I get these errors Error: Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead.
11 |
12 | async componentDidMount() {
13 | var citas_data = await makeRequest('api/products/');
> 14 | citas_data.data.map(data => (
15 | this.setState({
16 | data: [...this.state.data, [{ id: data._id, name: data.name },]]
17 | })
The solution was to change the name of the state "data" to a different one.
Example:
constructor() {
super();
this.state = {
data: []
}
}
To:
constructor() {
super();
this.state = {
dates: []
}
}
**try to do that**
async componentDidMount() {
const results=[]
const citas_data = await makeRequest('api/products/');
citas_data.forEach(item => {
results.push({
id: data._id,
name: data.name
});
});
this.setState({data:results});
I fetch data from json and try to display one of the arrays in my componenet but I get an error that map is not a function, what do I do wrong? How to get only one array of two? Is it array I have in json or an object?
import React, { Component } from 'react';
class Customer extends Component {
constructor() {
super();
this.state = {
customers : []
};
}
componentDidMount() {
fetch('myURL')
.then(response => response.json())
.then(json => this.setState({ customers: json}))
}
render () {
return (
<div>
{this.state.customers && this.state.customers.map(cust => (
<div>
<h1>{cust.CustomerName}</h1>
</div>
)
})}
</div>
)
}
}
export default Customer;
And my JSON file has two arrays that looks like this:
{
"fields": [
{
"id": "Customer_ID",
"description": "Customer ID",
"type": "Key",
},
{
"id": "Customer_ID",
"description": "Customer ID",
"type": "Key",
},
],
"list_items": [{"Customer_ID":1,"CustomerName":"ABS","CustomerType":"DTS"},
{"Customer_ID":2,"CustomerName":"Giu Sto","CustomerType":"STD"}]
}
You did not asign the items to customers in state. You should do it like this
componentDidMount() {
fetch('myURL')
.then(response => response.json())
.then(json => this.setState({ customers: json.list_items}))
}
I hope this solves your problem
Edit:
this.setState({customers:json}) will change customers state to an object which is not itterable and have the value of your json file customers:{fields: [...],list_items: [...]} but you only want list_items to be assigned to customers that's why you should access list_items from json and assign it directly to customers this.setState({customers:json.list_items_}
try logging whether the array is present or not.
const my_json = {
fields: [
{
id: "Customer_ID",
description: "Customer ID",
type: "Key",
},
{
id: "Customer_ID",
description: "Customer ID",
type: "Key",
},
],
list_items: [
{ Customer_ID: 1, CustomerName: "ABS", CustomerType: "DTS" },
{ Customer_ID: 2, CustomerName: "Giu Sto", CustomerType: "STD" },
],
};
my_json.list_items.map(customer => console.log(customer.CustomerName))
I want to structure the data that I get from a server, so I can use the TreeView component from Material UI: https://material-ui.com/api/tree-view/
I'm fetching large amounts of data so I want to fetch child nodes from the server when the user clicks on the expand button. So
when the first node is expanded a HTTP request is sent to a server which returns all of the children of that node. When another node is expanded the children of that node is fetched etc.
On startup of the page I want to fetch the root node and its children. The JSON returned will look something like this:
{
"division": {
"id": "1234",
"name": "Teest",
"address": "Oslo"
},
"children": [
{
"id": "3321",
"parentId": "1234",
"name": "Marketing",
"address": "homestreet"
},
{
"id": "3323",
"parentId": "1234",
"name": "Development",
"address": "homestreet"
}
]
}
When expanding the Marketing node I want to make a HTTP call to fetch the children of this node. So I would get JSON like this:
{
"children": [
{
"id": "2212",
"parentId": "3321",
"name": "R&D",
"address": "homestreet"
},
{
"id": "4212",
"parentId": "3321",
"name": "Testing",
"address": "homestreet"
}
]
}
But I am confused on how to create such a data structure which can later be used my the TreeView component. How can I create such a structure?
For anyone still looking for a solution to this problem I've recently tackled it using a combination of the selected and expanded props in the TreeView API. See this Code Sandbox demo for an example of how to asynchronously load new children and expand their parent once they are loaded.
import React from "react";
import TreeView from "#material-ui/lab/TreeView";
import ExpandMoreIcon from "#material-ui/icons/ExpandMore";
import ChevronRightIcon from "#material-ui/icons/ChevronRight";
import TreeItem from "#material-ui/lab/TreeItem";
import TreeNode from "./TreeNode";
const mockApiCall = async () => {
return new Promise((resolve) => {
setTimeout(() => {
const nextId = Math.ceil(Math.random() * 100);
resolve([
{
id: `${nextId}`,
name: `child-${nextId}`,
children: []
},
{
id: `${nextId + 1}`,
name: `child-${nextId + 1}`,
children: []
}
]);
}, Math.ceil(Math.random() * 1000));
});
};
export default class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: [],
selected: "1",
tree: new TreeNode({
id: "1",
name: "src",
children: []
})
};
}
handleChange = async (event, nodeId) => {
const node = this.state.tree.search(nodeId);
if (node && !node.children.length) {
mockApiCall()
.then((result) => {
this.setState({ tree: this.state.tree.addChildren(result, nodeId) });
})
.catch((err) => console.error(err))
.finally(() => {
this.setState({
selected: nodeId,
expanded: [...this.state.expanded, nodeId]
});
});
}
};
createItemsFromTree = (tree) => {
if (tree.children.length) {
return (
<TreeItem key={tree.id} nodeId={tree.id} label={tree.name}>
{tree.children.length > 0 &&
tree.children.map((child) => this.createItemsFromTree(child))}
</TreeItem>
);
}
return <TreeItem key={tree.id} nodeId={tree.id} label={tree.name} />;
};
render() {
return (
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
selected={this.state.selected}
onNodeSelect={this.handleChange}
expanded={this.state.expanded}
>
{this.createItemsFromTree(this.state.tree)}
</TreeView>
);
}
}
In my react application, I am implementing a tree view structure to display the api response in more readable format. I am using tree view-react-bootstrap for that.
import React from 'react';
import ReactDOM from 'react-dom';
import TreeView from 'treeview-react-bootstrap'
class Example extends React.Component {
constructor(){
super();
// SET YOUR DATA
this.state = {
data: [
{
text: "John Peter",
nodes: [
{
text: "ID: 11111",
nodes: [
{
text: "VIN"
},
{
text: "Policy Effective Date"
},
{
text: "Policy Expiration Date"
},
{
text: "Vehicle Make"
},
{
text: "Vehicle Model"
}
]
},
{
text: "ID: 123456",
nodes: [
{
text: "VIN"
},
{
text: "Policy Effective Date"
},
{
text: "Policy Expiration Date"
},
{
text: "Vehicle Make"
},
{
text: "Vehicle Model"
}
]
}
]
},
{
text: "Scott Brown"
}
]
}
}
render(){
return (
// RENDER THE COMPONENT
<TreeView data={this.state.data} />
);
}
}
export default Example
I am using dummy data for now but this is the format that I want my data to be displayed. The api response I have is "array of objects" and it is only in one level JSON format.
Sample response -
[
{
"id": "1234",
"name": "John Scott",
"vin": "45",
"make": "Toyota",
"model": "Etios"
},
{
"id": "4567",
"name": "James Scott",
"vin": "67",
"make": "Hyundai",
"model": "Etios"
}
]
If you see the response, I would like my key value to be printed in a tree structure.
Is there a way I can render this response to accommodate with treeview-react-bootstrap?
I am not sure if I need to use map function inside my render method to iterate and display the data and how will it work along.Can someone let me know if I am doing it right or is there any better way of doing it. thanks in advance.
You can transform the response something like this. Have just added a dummy response. Please check the following code and let me know if this helps:
import React from "react";
import ReactDOM from "react-dom";
import TreeView from "treeview-react-bootstrap";
import axios from "axios";
class Example extends React.Component {
constructor() {
super();
// SET YOUR DATA
this.state = {
data: []
};
}
componentDidMount() {
axios
.get("https://www.mocky.io/v2/5bb85d723000005f00f93bb6")
.then(data => {
let transformedData = data.data.map(d => {
return {
text: d.text,
nodes: [
{
text: "dummy 1",
nodes: []
}
]
};
});
this.setState({ data: transformedData });
});
}
render() {
return (
// RENDER THE COMPONENT
<TreeView data={this.state.data} />
);
}
}
ReactDOM.render(<Example />, document.getElementById("app"));
You can also see it in action here: https://codesandbox.io/s/73ryny9ywq?autoresize=1&hidenavigation=1
How to Make a Accessing data in an array, and list separated by categories Using axios React Native
I am trying to deploy a list with categories and products using axio in react native
my json structure
[
{
"id": "1",
"name": "TV",
"list": [
{
"idp": "1",
"namep": "TV 43"
},
{
"idp": "2",
"namep": "TV 32"
}
]
},
{
"id": "2",
"name": "Couch",
"list": [
{
"idp": "3",
"namep": "Couch for 3 people"
},
{
"idp": "4",
"namep": "Couch for 2 people"
}
]
}
]
what I've already done, so I can display categories
constructor(props) {
super(props);
this.state = { category: [], list: [] };
}
componentWillMount() {
axios.get('http://localhost/api/list.json')
.then(response => {
this.setState({
category: response.data,
list: response.data.list });
})
.catch(() => { console.log('Err'); });
}
.............
{this.state.category.map((item, i) => {
<Text>{item.name}</Text>
{ item.list.map((product, i) => {
<Text>{product.namep}</Text>
})}
})}
Example list
Sorry I can't give you a more detailed and focused answer since I'm not familiar with react native but logic goes like this:
A loop to iterate over main array and extract categories names then another loop inside that one for iterating over products.
const arr = [
{
"id": "1",
"name": "TV",
"list": [
{
"idp": "1",
"namep": "TV 43"
},
{
"idp": "2",
"namep": "TV 32"
}
]
},
{
"id": "2",
"name": "Couch",
"list": [
{
"idp": "3",
"namep": "Couch for 3 people"
},
{
"idp": "4",
"namep": "Couch for 2 people"
}
]
}
];
const parentEl = document.querySelector('#list');
arr.forEach((cat) => {
const catEl = document.createElement('div')
catEl.textContent = cat.name
parentEl.append(catEl)
cat.list.forEach((prod) => {
const listEl = document.createElement('ul')
const listItem = document.createElement('li')
listItem.textContent = prod.namep
listEl.append(listItem)
parentEl.append(listEl)
})
})
<div id="list">
</div>
So, not knowing react native AND assuming this code you pasted is correct, I'm going to risk saying it would go something like this:
{
this.state.category.forEach((item, i) => {
<Text>{item.name}</Text>
item.list.forEach((product, i) => {
<Text>{product.namep}</Text>
})
})
}