react native how to filter data with some key object on json - json

if I have json like this
-----------------
{
title: "The Basics - Networking",
description: "Your app fetched this from a remote endpoint!",
movies: [
{
title: "Star Wars",
category: "space",
releaseYear: "1977"
},
{
title: "Back to the Future",
category: "time"
releaseYear: "1985"
},
{
title: "The Matrix",
category: "scifi",
releaseYear: "1999"
},
{
title: "Inception",
category: "fantasy",
releaseYear: "2010"
},
{
title: "Interstellar",
category: "space"
releaseYear: "2014"
}
]
}
-----------------
I need to filter some data of category = space
but I don't know how to filter data after fetch json form webservice
I want only data form category = space
(It's mean I want to get interstellar and star wars)
and set to datasource
like a " dataSource: ds.cloneWithRows(responseJson.movies)" but this method get all row without filter
componentDidMount() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.movies),
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}

Use Array#Filter like this:
const movies = [{
title: "Star Wars",
category: "space",
releaseYear: "1977",
},
{
title: "Back to the Future",
category: "time",
releaseYear: "1985",
},
{
title: "The Matrix",
category: "scifi",
releaseYear: "1999",
},
{
title: "Inception",
category: "fantasy",
releaseYear: "2010",
},
{
title: "Interstellar",
category: "space",
releaseYear: "2014",
}
];
const space = movies.filter(x => x.category === 'space');
console.log(space);
Here you are another Array#Filter example,
filter posts where userId is 1.
https://jsonplaceholder.typicode.com/posts :
class Data extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
this.setState({ data: data.filter(d => d.userId === 1) })
})
.catch(error => {
console.error(error);
});
}
render() {
return (
<div>
<h1>Posts JSON:</h1>
<pre>
{JSON.stringify(this.state.data, null, 2)}
</pre>
</div>
);
}
}
ReactDOM.render(
<Data />,
document.getElementById('container')
);
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Related

How to get user information instead of just ID sequelize?

I am using sequelize with mysql,
I have 3 models
posts
Comments
users
posts model
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
title: DataTypes.STRING,
content: DataTypes.TEXT,
userId: DataTypes.INTEGER
}, {});
Post.associate = function(models) {
// associations can be defined here
Post.hasMany(models.Comment, {
foreignKey: 'postId',
as: 'comments',
onDelete: 'CASCADE',
})
Post.belongsTo(models.User, {
foreignKey: 'userId',
as: 'author',
onDelete: 'CASCADE',
})
};
return Post;
};
comments model
const user = require("./user");
module.exports = (sequelize, DataTypes) => {
const Comment = sequelize.define(
"Comment",
{
postId: DataTypes.INTEGER,
comment: DataTypes.TEXT,
userId: DataTypes.INTEGER,
},
{}
);
Comment.associate = function (models) {
// associations can be defined here
Comment.belongsTo(
models.User,
{
foreignKey: "userId",
as: "author",
me: "name",
},
{ name: user.name }
);
Comment.belongsTo(models.Post, {
foreignKey: "postId",
as: "post",
});
};
return Comment;
};
users model
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User",
{
name: DataTypes.STRING,
email: DataTypes.STRING,
},
{}
);
User.associate = function (models) {
// associations can be defined here
User.hasMany(models.Post, {
foreignKey: "userId",
as: "posts",
onDelete: "CASCADE",
});
User.hasMany(models.Comment, {
foreignKey: "userId",
as: "comments",
onDelete: "CASCADE",
});
};
return User;
};
and following is my response i am getting when i execute the following query
const getAllPosts = async (req, res) => {
try {
const posts = await models.Post.findAll({
include: [
{
model: models.Comment,
as: "comments"
},
{
model: models.User,
as: "author"
}
]
});
return res.status(200).json({ posts });
} catch (error) {
return res.status(500).send(error.message);
}
};
RESPONSE
"posts": [
{
"id": 1,
"title": "1st post ever on this server",
"content": "This is the content of the first post published on this type or architecture",
"userId": 1,
"createdAt": "2021-01-31T10:00:45.000Z",
"updatedAt": "2021-01-31T10:00:45.000Z",
"comments": [
{
"id": 1,
"postId": 1,
"comment": "this is the comment on first post",
"userId": 1, // Also need a key val pair of username and his email ID just instead of UserID
"createdAt": null,
"updatedAt": null
},
{
"id": 2,
"postId": 1,
"comment": "comment second",
"userId": 1,
"createdAt": "2021-01-31T15:34:27.000Z",
"updatedAt": "2021-01-31T15:34:27.000Z"
}
],
"author": {
"id": 1,
"name": "test user",
"email": "testuser#gmail.com",
"createdAt": null,
"updatedAt": null
}
}
]
}
I need the user name of commented user name and email for which i have fields in the table
but i am just getting user ID
how can i go about it,
I am very much new in sequelize, I tried but i am getting get same hasMany and benlongsTo results.
From what I see you doing, you need to run a nested include when getting the comment.
Try this modified code.
const getAllPosts = async (req, res) => {
try {
const posts = await models.Post.findAll({
include: [
{
model: models.Comment,
as: "comments",
include: [
{
model: models.User,
as: "author"
}
]
},
{
model: models.User,
as: "author"
}
]
});
return res.status(200).json({ posts });
} catch (error) {
return res.status(500).send(error.message);
}
};

GraphQL - operating elements of array

I would like to display some information about members, but I don't know how to resolve array of field 'time'. This is array, because it shows their login time. What should I do?
I used GraphQLString, but I am aware of this bad solution.
So I'm getting an error:
"message": "String cannot represent value: [\"12:08\"]",
Here is schema.js
const axios = require("axios");
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLSchema
} = require("graphql");
const memberType = new GraphQLObjectType({
name: "Member",
fields: () => ({
nick: {
type: GraphQLString
},
name_and_surname: {
type: GraphQLString
},
time: {
type: GraphQLString
}
})
});
//Root Query
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
users: {
type: new GraphQLList(memberType),
description: "List of members",
resolve(parent, args) {
return axios
.get("http://25.98.140.121:5000/data")
.then(res => res.data);
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
});
And here is JSON
[
{
"time": [
"12:08"
],
"nick": "Cogi12",
"name_and_surname: "John Steps"
},
{
"time": [
"12:16"
],
"nick": "haris22",
"name_and_surname": "Kenny Jobs"
},
{
"time": [
"12:07",
"12:08",
"12:17",
"12:19",
"12:45",
"13:25"
],
"nick": "Wonski",
"name_and_surname": "Mathew Oxford"
}
]
you can use GraphQLList along with GraphQLString for time type like this,
const memberType = new GraphQLObjectType({
name: "Member",
fields: () => ({
nick: {
type: GraphQLString
},
name_and_surname: {
type: GraphQLString
},
time: {
type: new GraphQLList(GraphQLString)
}
})
});

How to use json file fetch in react native

How should I use json data in flatlist?
This is the code I have
import React, { Component } from 'react'
import { Text, View, Button, YellowBox, FlatList, Image, ScrollView, Dimensions, TouchableHighlight } from 'react-native'
import Swiper from 'react-native-swiper'
import {styles} from '../style/styles'
class NavtexPage extends Component {
constructor(props) {//function
YellowBox.ignoreWarnings([
'Warning: componentWillReceiveProps is deprecated',
'Warning: componentWillUpdate is deprecated',
]);
super(props);
this.state = {
indexPage: 0,
isLoading: true,
}
}
//fetch API
componentDidMount = () => {
fetch('http://localhost:3000/jsondb/2',
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})//여기까지 fetch : requests
.then((response) => response.json())//fetch : response
.then((responseData) => {
console.log("성공 : ", responseData);
this.setState({
isLoading: false,
data: responseData
})
})
.catch((error) => {
console.error("api error : " + error.message);
});
}
//_renderItem how to json
_renderItem = ({ item, index }) => {
console.log('json : ', item);
}
render() {
return (
<View style={styles.container}>
<View style={{ flex: 0.1, backgroundColor: 'green' }}>
<Text>NAVTEX</Text>
</View>
<View>
<FlatList//i don't know
style={{ flex: 1, marginTop: 50, borderWidth: 1, borderColor: 'red' }}
data={this.state.data}
numColumns={1}
renderItem={this._renderItem}
// keyExtractor={(item, index) => item.no.toString()}
keyExtractor={(item => )}
/>
</View>//help
</View>
);
}
}
export default NavtexPage;
----------------------------ex.json
[
{
"Page1_1" :
[
{
"main_subject" : "asd",
"sub_subject" : "asd",
"mini_subject" : "asd",
"action" : "asd",
"action_img" : "",
"is_ok" : "1",
},
{
"main_subject" : "" ,
"sub_subject" : "",
"action" : "asd",
"action_img" : "",
"is_ok" : "",
}
]
},
{
"Page1_2" :
[
{
"main_subject" : "asd",
"sub_subject" : "asd",
"mini_subject" : "asd",
"action" : "asd",
"action_img" : "",
"is_ok" : "1",
},
{
"main_subject" : "" ,
"sub_subject" : "",
"action" : "Ping to 155.155.1.2 (NAVTEX TX2 at HF Site)",
"action_img" : "",
"is_ok" : "",
}
]
}
]
Firstly, you need to parse the json to array or object,then assign it to your flatlist data
.then((responseData) => {
let result = Json.parse(responseData)
// you data is array,and have page
let curPageData = result.page1_1
this.setState({
isLoading: false,
data: curPageData
})
})
You can try map function also.
sample code:-
this.state.data.map((data) => { //main data array
return(
data.map((insideData) => { //you can access page1_1 ... pages
return(
<Text>{insideData.main_subject}</Text>
.....
)
})
)
})

How to use map on json response returned by a REST API with ReactJs

I've a json. The only thing I want is title from the json.
{
"projects": [
{
"id": 1,
"title": "Bike Servicing System",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 2,
"title": "Air Traffic Controller",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 3,
"title": "Program Counter",
"language": "JavaFX",
"requires": "JDK 8"
}
],
"profile": {
"name": "typicode"
}
}
I am using fetch and componentDidMount. I want to do it musing map method to iterate through. Though I don't need <ul> and <li> tags really. I will remove them later. My React code is
import React, { Component } from "react";
class ProjectStack extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json.projects
});
});
}
render() {
var { isLoaded, items } = this.state;
var i=0;
if (!isLoaded) return <div>Loading...</div>;
return (
<div>
<ul>
{
items.map(item => (
<li key={item[i++].id}>
Projects: {item[i++].title}
</li>
))
}
</ul>
</div>
);
}
}
export default ProjectStack;
Apparently, there is something that I don't know because I am getting this error.
PS: This question is different from mine
The JSON of the URL you are fetching is this:
[
{
"id": 1,
"title": "Bike Servicing System",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 2,
"title": "Air Traffic Controller",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 3,
"title": "Program Counter",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 4,
"title": "Dove Tail",
"language": "JavaFX",
"requires": "JDK 8"
}
]
So for correctly set the data in the state you need to:
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
}
Besides correcting the error they have already told you related the map loop.
I found 2 mistakes from your code.
The first one is you didn't check the response data.
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
console.log(json); // it is an Array not object.
this.setState({
isLoaded: true,
items: json
});
});
And the second is you didn't use the map() properly.
/*{
items.map(item => (
<li key={item[i++].id}>
Projects: {item[i++].title}
</li>
))
}*/
// items has objects, so you should use map() like this.
{
items.map(item => (
<li key={item.id}>
Projects: {item.title}
</li>
))
}
The below code is one way to achieve what you want.
class ProjectStack extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
console.log(json);
this.setState({
isLoaded: true,
items: json
});
});
}
render() {
const {
isLoaded,
items
} = this.state;
console.log(items);
if (!isLoaded) return ( < div > Loading... < /div>);
return ( <
div >
<
ul > {
items.map(item => ( <
li key = {
item.id
} > Projects: {
item.title
} < /li>
))
} <
/ul> <
/div>
);
}
}
ReactDOM.render( <
ProjectStack / > , document.getElementById('root')
)
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>

Iterate a JSON array by a key value in react-native

Is there anyway to get a value in an object from a json array. I need to get a value from an object based on another value.
I have my code like:
export default class StandardComp extends Component {
constructor(props) {
super(props)
this.state = {
id: '',
email: 'abc#gmail.com',
dataSource: []
};
}
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({dataSource: responseJson})
//dunno what to do here
})
.catch((error) => {
console.error(error);
})
}
}
My "responseJson" is something like this. Then providing the key value (abc#gmail.com), how could I get the string "abcdef"?
[
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
}
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
]
Thank you in advance.
Find the element that matches email and return the id.
array::find
const data = [
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
},
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
];
const findIdByEmail = (data, email) => {
const el = data.find(el => el.email === email); // Possibly returns `undefined`
return el && el.id; // so check result is truthy and extract `id`
}
console.log(findIdByEmail(data, 'cat#gmail.com'));
console.log(findIdByEmail(data, 'abc#gmail.com'));
console.log(findIdByEmail(data, 'gibberish'));
The code will depend on how you get the value abc#gmail.com.
You'll probably need to pass it in as an argument to componentDidMount via a prop? Or extract it to a separate function. It just depends.
Something like this is the most basic way I'd say.
const value = responseJson.filter(obj => obj.email === 'abc#gmail.com')[0].id
Here it is implemented in your class.
export default class StandardComp extends Component {
...
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ dataSource: responseJson })
const { email } = this.state
const value = responseJson.filter(obj => obj.email === email)[0].id
})
.catch((error) => {
console.error(error);
})
}
}