react-native fetch api response parse to specific format - react-native

Below is my code to fetch a response from an API -
fetch('http://34.215.9.246:9000/api/chat/get-chat-messages-for-participant?participantId='+this.state.participantId+'&projectId='+this.state.projectId)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
var reponseApi=responseJson.stringify;
console.log(reponseApi)
// console.log((responseJson.stringify.replace("\"customizedChatmessage\": \"",'')).replace("\"",""));
this._isMounted = true;
this.setState(() => {
return {
messages: require('../../assets/data/messages.js'),
//messages: (responseJson.replace("\"customizedChatmessage\": \"",'')).replace("\"","")
};
});
})
.catch((error) => {
console.error(error);
});
the reponse of this api is :
[ {
"customizedChatmessage": "{_id: Math.round(Math.random() * 1000000), text: HI,user: {_id: 5a91138ce4b01f2df36531a5, name: alok sharama sir}, },"
},
{
"customizedChatmessage": "{_id: Math.round(Math.random() * 1000000), text: Hello World,user: {_id: 5a91138ce4b01f2df36531a5, name: alok sharama sir}, },"
},
{
"customizedChatmessage": "{_id: Math.round(Math.random() * 1000000), text: test message,user: {_id: 5a91138ce4b01f2df36531a5, name: alok sharama sir}, },"
}
]
i want to modify the response into a specific format into something shown below:
[{
_id: 516152, text: 'Hi',user: {_id: 1, name: 'Alok Sharma'},
},
{
_id: 396263, text: 'how r u ',user: {_id: 1, name: 'Alok Sharma'},
},
{
_id: 652380, text: 'image is not fine. cahnge it',user: {_id: 1, name: 'Alok Sharma'},
},
{
_id: 186058, text: 'image is not fine. cahnge it',user: {_id: 1, name: 'Alok Sharma'},
},
{
_id: 104931, text: 'image is not fine. cahnge it',user: {_id: 1, name: 'Alok Sharma'},
}]
Help me out to solve this issue. Thanks

Related

How to filter Sanity.io dataset based on a field on references

How to get all posts by a category slug in GROQ?
You can see that a post is added to one or more categories. I would like to get all posts by a category slug to show the posts on a category page. I am new to Sanity.io's GROQ. All the tutorials I have found on creating a blog with sanity.io and next.js have not covered it to show a category page showing posts from a category.
Post schema:
export default {
name: 'post',
title: 'Post',
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
{
name: 'slug',
title: 'Slug',
type: 'slug',
options: {
source: 'title',
maxLength: 96,
},
},
{
name: 'author',
title: 'Author',
type: 'reference',
to: {type: 'author'},
},
{
name: 'mainImage',
title: 'Main image',
type: 'image',
options: {
hotspot: true,
},
},
{
name: 'categories',
title: 'Categories',
type: 'array',
of: [{type: 'reference', to: {type: 'category'}}],
},
{
name: 'publishedAt',
title: 'Published at',
type: 'datetime',
},
{
name: 'body',
title: 'Body',
type: 'blockContent',
},
],
preview: {
select: {
title: 'title',
author: 'author.name',
media: 'mainImage',
},
prepare(selection) {
const {author} = selection
return Object.assign({}, selection, {
subtitle: author && `by ${author}`,
})
},
},
}
I have tried the following:
const query = `*[_type == 'post' && $slug in [categories[]-> {slug}] ]{ _id, title, slug, publishedAt, categories[]-> {title,slug}} | order(publishedAt) [0...10]`;
const posts = await client.fetch(
query,
{ slug }
);
console.log("posts", posts);
I got the solution at Sanity's slack channel. The following code helps to get the posts from a category by it's slug.
`*[_type == 'post' && $slug in categories[]->slug.current ]`;

GraphQLObjectType is not a constructor

I'm trying to follow a graphql tutorial, even thoughg I followed it and double checked I keep getting the above error and I have no idea why
dont you really hate when the bot asks you to type more, its mostly code for a reason I dont have a clue and I posted all my code!!!
const express = require("express");
const expressGraphQL = require("express-graphql");
const graphql = require("graphql");
const {
GraphQlSchema,
GraphQlObjectType,
GraphQLString,
GraphQLList,
GraphQLInt,
GraphQLNonNull,
} = graphql;
const app = express();
const authors = [
{ id: 1, name: "J. K. Rowling" },
{ id: 2, name: "J. R. R. Tolkien" },
{ id: 3, name: "Brent Weeks" },
];
const books = [
{ id: 1, name: "Harry Potter and the Chamber of Secrets", authorId: 1 },
{ id: 2, name: "Harry Potter and the Prisoner of Azkaban", authorId: 1 },
{ id: 3, name: "Harry Potter and the Goblet of Fire", authorId: 1 },
{ id: 4, name: "The Fellowship of the Ring", authorId: 2 },
{ id: 5, name: "The Two Towers", authorId: 2 },
{ id: 6, name: "The Return of the King", authorId: 2 },
{ id: 7, name: "The Way of Shadows", authorId: 3 },
{ id: 8, name: "Beyond the Shadows", authorId: 3 },
];
const BookType = new GraphQlObjectType({
name: "Book",
description: "A Book written by an author",
fields: () => ({
id: { type: GraphQLNonNull(GraphQLInt) },
name: { type: GraphQLNonNull(GraphQLString) },
authorId: { type: GraphQLNonNull(GraphQLInt) },
}),
});
const RouteQueryType = new GraphQlObjectType({
name: "Query",
description: "Root Query",
fields: () => ({
books: new GraphQLList(BookType),
description: "List of Books",
resolve: () => books,
}),
});
const schema = new GraphQlSchema({
query: RouteQueryType,
});
app.use(
"/graphql",
expressGraphQL({
schema: schema,
graphiql: true,
})
);
app.listen(5000, () => console.log("server running"));
Wrong capitilisation GraphQlObjectType should be GraphQLObjectType

Multiple filters / Filter inside filter - React Native

how can i do something like that in React-Native:
data = [
{id:1,title:'Action',games:[
{id:1,title:'Game1'},
{id:2,title:'Game2'},
{id:3,title:'Game3'},
]},
{id:2,title:'Horror',games:[
{id:1,title:'Game1'},
{id:2,title:'Game2'},
{id:3,title:'Game3'},
]},
]
Every time the query string is updated, look for the game within the category.
Returns only the categories that contain a game with the searched characters.
Thank you! :D
I don't know if I understand your question correctly. This is my solution.
If you query for "Game5" you will get whole object that contains query
const data = [
{
id: 1,
title: "Action",
games: [
{ id: 1, title: "Game1" },
{ id: 2, title: "Game2" },
{ id: 3, title: "Game3" },
],
},
{
id: 2,
title: "Horror",
games: [
{ id: 1, title: "Game4" },
{ id: 2, title: "Game5" },
{ id: 3, title: "Game6" },
],
},
];
const query = "Game5";
const result = data.find((category) =>
category.games.find((g) => g.title === query)
);
console.log(result);
You can use 'filter' instead of 'find' and result will be an array.
This is example of filter version. I add one more category so you can see how it filter
const data = [
{
id: 1,
title: "Action",
games: [
{ id: 1, title: "Game1" },
{ id: 2, title: "Game2" },
{ id: 3, title: "Game3" },
],
},
{
id: 2,
title: "Horror",
games: [
{ id: 1, title: "Game1" },
{ id: 2, title: "Game2" },
{ id: 3, title: "Game3" },
],
},
{
id: 3,
title: "Comedy",
games: [
{ id: 1, title: "Game5" },
{ id: 2, title: "Game6" },
{ id: 3, title: "Game7" },
],
},
];
const query = "Game2";
const result = data.filter((category) =>
category.games.find((g) => g.title === query)
);
console.log(result);
And you might want to look at life cycle componentDidUpdate if you write class component, but if you write function component you might want to use useEffect
This is official react hook explaination
EDIT: from your comment you might want something like this
const data = [
{
id: 1,
title: "Action",
games: [
{ id: 1, title: "Game1" },
{ id: 2, title: "Game2" },
{ id: 3, title: "Game3" },
],
},
{
id: 2,
title: "Horror",
games: [
{ id: 1, title: "Game1" },
{ id: 2, title: "Game2" },
{ id: 3, title: "Game3" },
],
},
{
id: 3,
title: "Comedy",
games: [
{ id: 1, title: "Game5" },
{ id: 2, title: "Game6" },
{ id: 3, title: "Game7" },
],
},
];
const query = "Game5";
let result = null;
data.forEach((category) => {
const game = category.games.filter((g) => g.title === query);
if (game.length) result = { ...category, games: game };
});
console.log(result);

populate mongoose key as part of object

EDIT
minimal reproduction repo
It's easier to explain in code than English.
The following code works, but it feels like there's gotta be an easier, more MongoDBy/mongoosy way ...
// recipeModel.js, relevant part of the schema
equipments: [{
_id: {
type: Schema.Types.ObjectId,
ref: 'equipments',
},
quantity: {
type: Number,
required: true,
},
}],
// recipeController.js
const equipmentsWorkaround = recipe => Object.assign({}, recipe.toObject(), {
equipments: recipe.toObject().equipments.map(equip => ({
quantity: equip.quantity,
name: equip._id.name,
_id: equip._id._id,
})),
})
const getItem = (req, res, next) => {
Recipes.findById(req.params.id)
.populate('equipments._id')
.then(equipmentsWorkaround) // <--- ugh ...
.then(recipe => res.json(recipe))
.catch(next)
}
I know how to do a "conventional" ref in mongoose, but is what I'm after here even possible in mongo?
desired outcome:
equipments: [
{
quantity: 1,
name: "Pan",
_id: 'some mongo object here...'
},
{
quantity: 3,
name: "Big Knife",
_id: 'some mongo object here...'
}
]

show comments like facebook with express

I have the next Schema:
var eventSchema = mongoose.Schema({
title: 'string',
propietary_id: 'String',
comments : [{
text: 'string',
user: { type : mongoose.Schema.Types.ObjectId, ref : 'users' },
createdAt: {type: Date, default: Date.now }
}]
});
my query:
Event.find().populate('comments.user').exec(function(err, doc){
console.log(err);
console.log(doc);
});
it's possible return object with events information, 2 comments and total number of comments (like facebook) ?
I would do it like this:
var NBR_OF_COMMENTS = 2;
Event.find().populate('comments.user').exec(function(err, event){
var comments = event.comments;
var totalNbrOfComments = comments.length;
comments.splice(NBR_OF_COMMENTS, totalNbrOfComments - NBR_OF_COMMENTS);
event.comments = {
count: comments.length,
total: totalNbrOfComments,
items: comments,
};
res.json(event);
});
For example, this should return the following:
{
title: 'test',
property_id: '123',
comments: {
count: 2,
total: 5,
items: [
{
text: 'comment 1',
...
},
{
text: 'comment 2',
...
},
],
}
}