Values not being mapped to object when getting element - arrays

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.

Related

React store data in a variable from API

I am trying to store some of my data in a const variable. Like I am getting FAQ section data from an API call. Like this one, I have my data in restaurant.faq and there can be multiple data so I map through it and it is working perfectly. Suppose Now I have two questions and two answers and I am getting it perfectly.
{restaurant.faq?.map((f) => (
<ListGroup.Item key={f.id}>
Question - <strong>{f.question}</strong>
<br />
Answer - <strong>{f.answer}</strong>
</ListGroup.Item>
))}
But I want to pass the same question and answer from this restaurant.faq in a const variable
Like this in rows [{question, answer}] section. How Can I do this?
const data = {
title: "FAQ",
rows: [
{
question: "Lorem ipsum dolor sit amet,",
answer: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed tempor sem. Aenean vel turpis feugiat,
ultricies metus at, consequat velit. Curabitur est nibh, varius in tellus nec, mattis pulvinar metus.
In maximus cursus lorem, nec laoreet velit eleifend vel. Ut aliquet mauris tortor, sed egestas libero interdum vitae.
Fusce sed commodo purus, at tempus turpis.`,
},
{
question: "Nunc maximus, magna at ultricies elementum",
answer:
"Nunc maximus, magna at ultricies elementum, risus turpis vulputate quam, vitae convallis ex tortor sed dolor.",
},
],
};
Update how to do the same with this one?
{restaurant.menu?.map((men) => (
<ListGroup.Item key={men.id}>
<Image src={men.image} alt={men.name} style={{height:'250px', width:'1800px'}} fluid />
</ListGroup.Item>
))}
const images = [
{
original: 'https://picsum.photos/id/1018/1000/600/',
},
{
original: 'https://picsum.photos/id/1015/1000/600/',
},
{
original: 'https://picsum.photos/id/1019/1000/600/',
},
];
You can do like this
const data = {
title: "FAQ",
rows: restaurant.faq?.map(({ question, answer}) => (
{ question,
answer
})
)

How to target a specific element in react map loop

I have comments that i loop through:
When i click on the three dots i want there to pop a little div out with the text "repport comment".
But when i click on one of buttons they all open :
import { FaEllipsisV } from "react-icons/fa";
import "./styles.css";
import React from "react";
const data = [
{
postId: 1,
id: 1,
name: "id labore ex et quam laborum",
email: "Eliseo#gardner.biz",
body:
"laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
postId: 1,
id: 2,
name: "quo vero reiciendis velit similique earum",
email: "Jayne_Kuhic#sydney.com",
body:
"est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
{
postId: 1,
id: 3,
name: "odio adipisci rerum aut animi",
email: "Nikita#garfield.biz",
body:
"quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
},
{
postId: 1,
id: 4,
name: "alias odio sit",
email: "Lew#alysha.tv",
body:
"non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati"
},
{
postId: 1,
id: 5,
name: "vero eaque aliquid doloribus et culpa",
email: "Hayden#althea.biz",
body:
"harum non quasi et ratione\ntempore iure ex voluptates in ratione\nharum architecto fugit inventore cupiditate\nvoluptates magni quo et"
}
];
export default function App() {
const [showOptions, setShowOptions] = React.useState(false);
return (
<div className="App">
{data.map((comment, index) => (
<div key={index} className="comment-container">
{comment.name}
<button onClick={() => setShowOptions(!showOptions)}>
<FaEllipsisV />
</button>
{showOptions ? (
<div className="options">Report this comment</div>
) : null}
</div>
))}
</div>
);
}
https://codesandbox.io/s/elated-roentgen-fbjr7?file=/src/App.js:0-2121
Example of what i'd like :
You can do something like this:
export default function App() {
const [showOptions, setShowOptions] = React.useState({ id: null, status: false });
return (
<div className="App">
{data.map((comment, index) => (
<div key={index} className="comment-container">
{comment.name}
<button onClick={() => setShowOptions({ id: comment.id, status: !showOptions.status })}>
<FaEllipsisV />
</button>
{showOptions.status && comment.id === showOptions.id ? (
<div className="options">Report this comment</div>
) : null}
</div>
))}
</div>
);
}

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);
})
}

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 call single api in multiple react component with mixed up server side code?

Below is my nested object json, where i want access the properties in different react component
{
"Created":"2017-02-09",
"SenderOrReceiver":"Not developed yet",
"PageResponsible":"Yogesh Shinde",
"LastUpdated":"2017-02-09",
"ExternalLinks":[
{
"Id":null,
"Title":"Yahoo",
"Url":"http://yahoo.com"
},
{
"Id":null,
"Title":"Facebook",
"Url":"http://facebook.com"
}
],
"InternalLinks":[
{
"Id":null,
"Title":"Google",
"Url":"~/link/23199285feef4501987b5fa452e49b94.aspx"
}
],
"Appendices":[
{
"Id":null,
"Title":"React",
"Url":"~/link/23199285feef4501987b5fa452e49b94.aspx"
}
],
"ContactDetails":{
"Email":"user#gmail.com",
"Information":"Aliquam mollis, quam nec suscipit placerat, nibh est efficitur urna, in ornare mauris eros eu tortor. Nulla fermentum hendrerit mi, nec luctus nunc auctor at. Nullam sagittis posuere libero, eget imperdiet neque. Etiam ac lacus diam. Mauris sapien turpis, lobortis non eros in, porttitor dapibus ipsum.",
"Name":"user1",
"Telephone":"11234"
},
"Subject":[
"Lorem"
],
"HeadingLinks":[
{
"Id":"headinglink1",
"Title":"Heading1",
"Url":"/sv/news-page/#headinglink1"
}
]
}
Below is my server side index.cshtml (Layout)
#model intrav2.infrastructure.ViewModels.Pages.NewsPageViewModel
<div class="l-content_primary" role="main">
<div id="breadcrumb"></div>
<h2>#Html.PropertyFor(x => x.CurrentPage.Heading)</h2>
<div id="newcreatedinfo"></div>
<div>#Html.PropertyFor(x => x.CurrentPage.Media)</div>
<p class="preamble">#Html.PropertyFor(x => x.CurrentPage.Preamble)</p>
<div id="newsHeadingLinks"></div>
<p>#Html.PropertyFor(x => x.CurrentPage.MainBody)</p>
#Html.PropertyFor(x => x.CurrentPage.ExtraInformation)
<div id="newspagecontent"></div>
</div>
<aside class="l-blocks_secondary" role="complementary" id="newsSiderBar"></aside>
Now i want,
Created/SenderOrReceiver property in newcreatedinfo
External and Internal links in newspagecontent
Appendices/Contact in side content on page

Resources