How can i access data by url name? - reactjs

Im using NextJs, im a beginner. I want to take data by urlname. I have a data with categories,
export const products = {
"orthopedics": [
{
"id": 0,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "sergei orthopedics indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
},
{
"id": 1,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "sergei orthopedics indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
}
],
"bandageAndPatch": [
{
"id": 0,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "segei bandageAndPatch indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
},
{
"id": 1,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "segei bandageAndPatch indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
}
],
"woundRecovery": [
{
"id": 0,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "segei woundRecovery indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
},
{
"id": 1,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "segei woundRecovery indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
}
],
"surgery": [
{
"id": 0,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "segei surgery indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
},
{
"id": 1,
"img": "https://sterilno.com/netcat_files/multifile/2385/proteoks_tm.jpg",
"title": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, error!",
"brend": "segei surgery indstruies",
"price": 4242,
"altDescription": "фото того то продукта"
}
]
}
And i have a catalog menu in my webpage, each of them go to the personal page
`/catalog/${i.link}` - for instance /catalog/orthopedics
This is my component(statick page) by categories, in this page i want to render data by categories name from url. I tryed to add url name to access
const CatalogPage:FC = ({data}:any) => {
const router = useRouter();
const nameUrl = router.query.category; // url name
const currentData = data.nameUrl // deesn work - undefiend
console.log(currentData)
return (
<CatalogLayot>
<h1>{`${nameUrl} catalog page by category`}</h1>
{/* {currentData .map((i:any) => (
<Card
title={i.title}
brend={i.brend}
img={i.img}
price={i.price}
key={i.id}
altDescription={i.altDescription}
id={i.id}
/>
))} */}
</CatalogLayot>
)}
export default CatalogPage;
export async function getServerSideProps(){
const {products} = await import('#/data/db');
return{
props:{
data: products
}
}
}
This is a pet project, so i can change whatever i want

Related

Values not being mapped to object when getting element

What I want:
I want to get values for a JSON object declared like:
Tickets.json
[
{
"ticket_id": 13,
"user_id": 1,
"country_code": "+267",
"mobile_number": 74111111,
"email": "tdjlknds#sdmnnsd.com",
"policy_number": 7411235,
"category": "Unable to pay for cover",
"description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui",
"created_date": "2021/01/16 08:45:01",
"status": "IN PPROGRESS"
},
{
"ticket_id": 2,
"user_id": 2,
"country_code": "+267",
"mobile_number": 72654867,
"email": "tdjlknds#sdmnnsd.com",
"policy_number": 1243456,
"category": "Other",
"description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui",
"created_date": "2021/01/16 08:45:01",
"status": "WAITING CUSTOMER FEEDBACK"
}
]
And map it to an interface object in another .tsx file like this:
TicketCard.tsx
interface IViewTickets {
type: string;
userObj: {
ticket_id: number;
user_id: number;
country_code: string;
mobile_number: number;
email: string;
policy_number: number;
category: string;
description: string;
created_date: string;
status: string;
};
}
const TicketCard: React.FC<IViewTickets> = (props) => {
// some code
}
To do this I am using the below:
Dashboard.tsx
return (
<React.Fragment>
<div className="mainDashboardDiv">
<div id={`${styleId}`}>
{
Tickets.map(function (item, index) {
return ([
<DisplayList key={index} type="Open" userObj={item} />
]);
})
}
</div>
</div>
</React.Fragment>
)
I want to be able to use userObj to populate a the dashboard with all the json array items but I keep getting the error:
TypeError: Cannot read property 'policy_number' of undefined
I've tried a lot of things:
Using index or idx to pass on the index of an array
Rendering the json to an object array and using a loop to pass on values
adding a key value of the ID from the json
I keep getting the same error and console.log() shows that I'm not passing anything to the other file
Other ticketCard.tsx return define like:
return (
<Fragment>
<Card tokens={cardTokens} className="ticketCard animated fadeInLeft" compact={false}>
<Card.Item>
<Persona text={policy_string} secondaryText={tickets.created_date} />
</Card.Item>
<Card.Section>
<Text variant="small" styles={siteTextStyles}>
{tickets.category}
</Text>
<Text styles={descriptionTextStyles}>{tickets.ticket_id}</Text>
<Text variant="small" styles={helpfulTextStyles}>
{tickets.description}
</Text>
</Card.Section>
<Card.Section horizontal styles={footerCardSectionStyles} tokens={footerCardSectionTokens}>
<PrimaryButton className="cardButton" text={props.type} onClick={openTicketChat}/>
</Card.Section>
</Card>
</Fragment>
)
I just realized that I did it properly and the actual problem was that I called TicketCard.tsx instead of Dashboard.tsx.
When I fixed that issue, they showed up just fine.

Change position of objects inside an array

I have a functional component which has a useState that contains the information i want to display and the images.
const [images, setImages] = useState(
[
{
"index": 0,
"img": Volleyball,
"text": ' Lorem ipsum dolor, sit amet consectetur adipisicing elit. Libero ut dolorem dolore modi esse reprehenderit assumenda error aut ducimus, aliquam repudiandae aliquid deserunt voluptatum placeat fugit explicabo dignissimos cum tempore.'
},
{
"index": 1,
'img': Gaming,
"text": ' Lorem ipsum dolor, sit amet consectetur adipisicing elit. Libero ut dolorem dolore modi esse reprehenderit assumenda error aut ducimus, aliquam repudiandae aliquid deserunt voluptatum placeat fugit explicabo dignissimos cum tempore.'
},
{
'index': 2,
'img': Coding,
"text": ' Lorem ipsum dolor, sit amet consectetur adipisicing elit. Libero ut dolorem dolore modi esse reprehenderit assumenda error aut ducimus, aliquam repudiandae aliquid deserunt voluptatum placeat fugit explicabo dignissimos cum tempore.'
}
]
)
And this is the jsx that I have in the return body with a left button that prevImage function.
return (
<div className={classes.gallary}>
<div className={classes.direction}>
<button className={classes.leftArrow} onClick={prevImage}>Left</button>
<button className={classes.rightArrow} >Right</button>
</div>
<div className={classes.images}>
{images.map(current => {
return (
<div key={current.index}>
<img src={current.img} alt="" className={classes.image} />
</div>
)
})}
</div>
</div>
);
Here is the prevImage function :
const prevImage = () => {
const currentImgArray = [...images];
const sendToBack = currentImgArray.push(currentImgArray.pop());
setImages(sendToBack)
}
This is what it looks like before clicking the button and what I am trying to do is to place the first object as the last object in the array . If the function is called I get : "TypeError: images.map is not a function"
As has been pointed out, array::push returns the new length of the array, not an array. Basically you need to rotate the array left/right.
const prevImage = () => {
// moves last image to front of array
setImages(images => [images[images.length - 1], ...images.slice(0, -1)]);
};
const nextImage = () => {
// moves first image to end of array
setImages(images => [...images.slice(1), images[0]]);
};
Array.push returns new length of the array, so concat function is to be use on here:
const prevImage = () => {
const currentImgArray = [...images];
const sendToBack = currentImgArray.concat(currentImgArray.pop());
setImages(sendToBack)
}
Updated ans:
const prevImage = () => {
setImages(prevState => {const popArr = prevState.pop();
return prevState.concat(popArr);
})
}

fetch data in react returns {}

I have a react component , and I want to fill its state by fetching data from the url that I tested in browser and returns json data . but in my code I got nothing, here is my code :
fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json`)
.then(response => response.json())
//.then(data => JSON.stringify(data))
.then(data => this.setState({
latitude: position.coords.latitude, // this ois ok
longitude: position.coords.longitude, /// this is ok
locations : data // here I get {}
}));
Problem is here in my render function
const { location } = this.state.locations;
alert("1" +JSON.stringify( this.state.locations));
alert("2" + JSON.stringify( location));
First alert is full with correct data but second alert returns undefined.
It looks like you're trying to destructure location from this reponse:
{
"posts": [
{
"_id": "5b3f761e21d434001487ad99",
"title": "Hello Word!",
"content": "The world is green!",
"__v": 0
},
{
"_id": "5b3f76b521d434001487ad9a",
"title": "Sed porttitor lectus nibh",
"content": "Sed porttitor lectus nibh. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Pellentesque in ipsum id orci porta dapibus. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Pellentesque in ipsum id orci porta dapibus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.",
"__v": 0
}
]
}
As you can see, it doesn't have a location property so the result of your destructure will be undefined. Are you hitting the right endpoint?

How to update array of object in reactjs

I can't figure out how to change state in my app correctly. For example, I want change 'modalStatus' key of a particular post to true, what should I write in my showModal function? I have the following data-structure:
class App extends React.Component {
constructor() {
super();
this.state = {
posts: [
{
'author': 'Adolf Hitler',
'img': 'http://www.jewishvirtuallibrary.org/images/hitler1.jpg',
'content': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
},
{
'author': 'Iosif Stalin',
'img': 'http://xn--h1aagokeh.xn--p1ai/wp-content/uploads/2016/07/46432404.jpg',
'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
},
{
'author': 'Napoleon Bonapard',
'img':'http://cdn.history.com/sites/2/2015/04/hith-6-things-you-should-know-about-napoleon-E.jpeg',
'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
},
{
'author': 'Vladimir Putin',
'img':'http://realnienovosti.com/images/148795554214.jpg',
'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
}
]
};
And function that is responsible for changing the state:
showModal () {
this.setState(do something)
}
Write it like this, pass a index to this function whose value you want to edit,
showModal (index) {
var posts = JSON.parse(JSON.stringify(this.state.posts));
posts[index].modalStatus = true;
this.setState({posts});
}
Check the DOC.
Or You could use the update immutability helper for this:
this.setState({
posts: update(this.state.posts, {0: {modalStatus: {$set: true}}})
})
You can do it like that:
showModal () {
var item = this.state.posts[0];
item.modalStatus = true;
this.setState({});
}
After that - React will re-render your component according to new state object.

How to change icon marker with angularjs and google maps

im working in phonegap project with angularjs google maps (https://github.com/allenhwkim/angularjs-google-maps)
I need to change default icon marker with custom images.
This is my controller code:
core.js
// Map Markers Controller
app.controller('markersController', function($scope, $compile){
$scope.infoWindow = {
title: 'title',
content: 'content'
};
$scope.markers = [
{
'title' : 'Location #1',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7112, -74.213]
},
{
'title' : 'Location #2',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7243, -74.2014]
},
{
'title' : 'Location #3',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7312, -74.1923]
}
];
$scope.showMarker = function(event){
$scope.marker = $scope.markers[this.id];
$scope.infoWindow = {
title: $scope.marker.title,
content: $scope.marker.content
};
$scope.$apply();
$scope.showInfoWindow(event, 'marker-info', this.getPosition());
}
});
And this is my markers.html
<div ng-controller="markersController" class="map-fullscreen-container">
<map zoom="8" center="[-26.82, -54.84]" class="fullscreen">
<info-window id="marker-info">
<div ng-non-bindable="">
<strong class="markerTitle">{{ infoWindow.title }}</strong>
<div class="markerContent">
<p>{{ infoWindow.content }}</p>
</div>
</div>
</info-window>
<marker ng-repeat="(id, marker) in markers" id="{{ id }}"
position="{{marker.location}}"
on-click="showMarker(event, $index)" >
</marker>
</map>
</div>
If you only have one marker, you can set it up directly on your marker directive:
<marker ng-repeat="(id, marker) in markers" id="{{ id }}"
position="{{marker.location}}"
on-click="showMarker(event, $index)"
icon="yourIconUrl.png" >
</marker>
If you have different markers for each item, the first thing you need to do is to add the icon property to your items:
$scope.markers = [
{
'title' : 'Location #1',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7112, -74.213],
'icon' : 'yourIconUrl.png'
},
{
'title' : 'Location #2',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7243, -74.2014],
'icon' : 'yourIconUrl.png'
},
{
'title' : 'Location #3',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7312, -74.1923],
'icon' : 'yourIconUrl.png'
}
];
Then you need to use it on your html, by adding it to the marker directive:
<marker ng-repeat="(id, marker) in markers" id="{{ id }}"
position="{{marker.location}}"
on-click="showMarker(event, $index)"
icon="{{marker.icon}}" >
</marker>
That's it, hope that helps.
Please refer to the documentation for more info:
https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/docs/index.html

Resources