Implementing javascript / json objects in ReactJS - javascript

I want to create some kind of temporary "database" for my test project.
What is the best solution to store those objects inside React app and how to access it in different components?
To clear what I mean, I've got a search bar, after enter is pressed the function would go through the "database" and if database.title is equal to user input a new div would be rendered with object details after a button is clicked.
I would be grateful for pointing me in the right direction.

You can create a dummy data file containing an array or some sort of data in it and then import it in which component you want to test.
Example:
// dummyData.js
const dummyData = [
{
title: 'this is a title',
type: 'book'
},
{
title: 'this is another title',
type: 'movie'
},
{
title: 'this is a foo',
type: 'bar'
}
];
export default dummyData;
// on your component
import dummyData from '/path/to/your/dummyData.js';

Related

feathers js get custom attribute value

I'm first time using feathers and Sequelize.
I want ask something for the example I have data user
name: 'user b',
email:'userb#mail.com',
createdAt:'2022-02-02',
updatedAt: '2022-02-02',
}
my expected return
name: 'user b',
email: 'userb#mail.com',
}
but I got all data user b
You can use the after hook to delete the properties that you don't want to get.
Or you can use the feathers.js common querying to deselect the specific fields and querying is the better approach.
Still, if you want to use the hooks, here is the code example:
after: {
get: [ (context) => {
delete context.result.data.fieldName;
}
}

Why wont my data render onto my card component when using spread operator?

I am trying to render data from a data file onto my card component by destructuring an object and using the spread operator (apologies if my jargon is wrong I don't know the exact words to describe it). I have done this in a project previously and tried to copy how I did it but the data will not render - get no issues in the console either.
I have made a code sandbox for it here - you will want to open it in a new window to see the card component in action as I have not made a responsive layout yet so it wont render on smaller screens.
The important files relevant to this are:
PortfolioCardData.js (stores the data which is exported)
PortfolioPageHero.js (where the AnimatedCard is rendered and I spread the data as an object into the card)
AnimatedCard.js & AnimatedCardDetails.js - where I destructure an object in the functions parenthesis and then use objects to place where the title, image etc will go
The issue is in the file PortfolioPageHero.js where you are passing data by destructuring to
<AnimatedCard {...PortfolioCardData1}/>
where PortfolioCardDetails1 is an array of objects
export const PortfolioCardData1 = [
{
key: 2,
image: "",
title: "Recipe App",
subtitle: "Built with React | Mobile First",
buttonText: "Take a look"
}
]
so when you use spread operator on array to pass the data then that array is passed as a key-value pair of index : valueAtIndex somthing like this
"0": {
key: 1,
image: "",
title: "Ecommerce",
subtitle: "Built with react | Redux | Stripe",
buttonText: "Take a look"
}
so, you can access this data by doing props.0.image , etc or you can spread the object while destructuring like this
<AnimatedCard {...PortfolioCardData1[0]}/>
then your current code would work.

Handling updates on nested screens using Context and React Navigation in React Native

Let's say I am building a shopping list app. I have the ability to create different shopping lists. I have three screens:
-- Shopping Lists: displays all the lists
---- List Details: displays all the items from a list
------ List Item Details: displays all the info about an item
To store the state and avoid prop drilling I use Context. My state could look like:
shoppingLists = [
{
title: 'Groceries',
items: [{
name: 'Apples',
quantity: 3
... (other info)
},
items: [{
name: 'Oranges',
quantity: 6,
...
}]
},
{
title: 'Office Supplies',
items: [{
name: 'Paper',
quantity: 2
... (other info)
},
items: [{
name: 'Pens',
quantity: 25,
...
}]
}]
When I tap on a Shopping List on the Shopping Lists screen I do
navigation.navigate('ListDetails', {params: listItem})
In the List Details screen I have de ability to change the quantity of an item or delete them. If I do any of this actions I have to make an API call to my server to update the value on the database. Here are my questions:
Currently I store the values in a local variable in my screen for example:
const [title, setTitle] = useState(props.route.params.title)
const [items, setItems] = useState(prop.route.params.items)
And if I make a change in the quantity I use setState to update my local array and then make an API call to update the context. This results problematic when adding more nested screens.
For example if I would give the user the ability to change the item quantity in the List Item Details screen, when the user goes back to the List Details screen, the values would not be updated.
My question is, which is the correct way to grab the state of the context and update it locally?
For example should I do something like:
navigation.navigate('ListDetails', {params: { listName: 'Groceries' })
And then in my List Details screen grab the correct list from the array like:
const {lists} = useContext(ShoppingLists)
const list = lists.filter(l => l.title === props.route.params.title)
What is the correct way?
The other question I have is a more general question. I want to use optimistic responses: when the user updates the quantity of an item in the list I update it locally and send the request to the server. If there's an error rollback the change. Which would be the correct way of doing this?
Thanks!
I would advise against updating context data in such a way. You could create a setList() method in the context instead, or updateList() to aggregate new data to the existing data.
This is related to the previous one. You could wrap the logic of POSTing to the server in a try-catch block and throw an error when it's not successful. Then you can set the new value only when it's successful. Another option would be to return the promise, so you could handle errors from outside, like setList().then(response => {}).catch(error => {}) though I don't think this looks that good.
Think you're over complicating it and also in your list you're not showing an id for each item. You should build your database with all the items and their unique id then call upon that when needed. The id should never change and that's easier to pass around and reference.
For example you can build an object in context with just the id and quantity and use useReducer for this:
https://reactjs.org/docs/hooks-reference.html#usereducer

Implement filter options in Gatsby

I'm fairly new to Gatsby and React and I couldn't find an answer to my problem.
I want to be able to have filtering options on the home of my website that allow the user to display only content relevant to that filter.
Let's say my posts are recipes and they are categorized by type: main, snack and dessert.
I want a filter, can be a button or a drop-down it doesn't matter, and when the user selects it I will display only the items relevant. Ideally I'm going to have multiple filters, around 4-5 for different properties of the frontmatter of my posts .
From what I understand it's not really something I can do with graphql because after build I cannot access it anymore so I was seeking some advice from more experienced devs.
If you have a small set of posts, I think you can make a search component that get all the posts & then use something like js-search or flexsearch to index them.
In a non-page component (not in src/pages folder), you can use StaticQuery to get all the posts' info.
Say you have this graphql query result:
data: {
allMarkdownRemark: {
edges: [{
node: {
id: '1234-1233...',
fields: {
slug: '/hello/'
},
frontmatter: {
title: 'hello',
tags: [ 'go', 'js' ]
}
}
}, {
node: {
id: ...
}
}]
}
}
Then you can index & search for post, say, with js-search:
const posts = data.allMarkdownRemark.edges.map(({ node }) => node) // unwrap edges
const postIndex = new JsSearch.Search('id')
postIndex.addIndex(['frontmatter', 'tags']) // index node.frontmatter.tags
postIndex.addIndex(['frontmatter', 'title'])
postIndex.addDocuments(posts) // add data to array
const results = postIndex.search('go')
console.log(results) // [{ id: '1234-1233...', frontmatter: { title: 'hello', tags: [ 'go', 'js' ]}}]
Then you can store this result in, say, the component's state & render the results as posts.
Gatsby's doc also has a guide on adding search to your site, though I think the js-search part is a bit overwhelming.

How to get the associated store in Sencha Touch?

Hi I am working with Sencha Touch app, and I have in a one store called "Customers" one model associated, I know when you create a model associated, automatically you create a new store in background, my question is: How to get this store called "templatesStore" (I see the result in the Chrome console) to filter later?
Thank you in advance.
It can be done using following syntax:
<mainStore>.getAt(0).<assosiationName>();
For example,if main store is "Customer" & name given in association as 'Template' then:
Association given in Customer model:
hasMany: [
{
model: 'sample.model.Template',
associationKey: 'templates',
name: 'templates' // name given here will be accessed from main store
},
]
For getting the template store:
Ext.getStore('Customer').getAt(0).templatesStore;
or
Ext.getStore('Customer').getAt(0).templates();
For filtering 'Customer' store based on template value:
Ext.getStore('Customer').filter([
{ filterFn: function (item) {
item.templatesStore.filter('templateValue',templateValue); // templateValue contains the value of selected template
if(item.templatesStore.getCount()>0)
return true;
else
return false;
}
}
]);

Categories