How to map the selected data in reactjs - reactjs

I can get the data from what i selected
const onHandleSelectLocation = async (value) => {
console.log(value)
}
this is the data result from console.log
I am having a hard time getting the Email only, how can i achieve that? i've tried the value.email but it getting undefined.

The value shown in the log is array of objects, if you want to get the email, do the map instead
const onHandleSelectLocation = async (value) => {
console.log(value);
const emails = value.map(({ email }) => email);
console.log(emails);
}

value is an array with two objects, that includes email, id and name. if you want to access one of those, you can use map. you can mapping in array and use what properties that you need from objects.
for example like this:
value.map => ( item => <div key={item.id}> {item.email} </div>)

Related

react ant design table with json - updating data without key problem

I would like to display some json data (coming from my backend and handled in a hook) in a similar way to this : https://ant.design/components/table/#components-table-demo-tree-data
I have a column with a checkbox and a column with an input (both must be editable by the user) and the final json state must be updated with the new datas.
Here you can find the structure of my json : https://pastebin.com/wA0GCs1K
Here you have a screen of the final result :
The code I used to fetch the data :
const [dataServiceInterface, setDataServiceInterface] = useState(null);
useEffect(() => {
CreateApiService.fetchDataServiceInterface(questionFiles, responseFiles).then((result) => {
if (result != null) {
setDataServiceInterface(result);
}
});
}, []);
Here you have the code I used to update the attributes (column constant for the second part) :
const onInputChange = (key, record, index) => (e) => {
e.preventDefault();
console.log(key);
console.log(index);
console.log(record);
console.log(e.target.value);
dataServiceInterface.itemsQ[index][key] = e.target.value;
};
// some other code here
{
title: "Json Name",
dataIndex: "name",
key: "name",
render: (text, record, index) => (
<Input
//defaultValue={text}
value={text}
onChange={onInputChange("name", record, index)}
/>
),
},
Problem is (I think) : As I dont have a key defined in my json datas (parents and children), when I try to update the children it dosent work. I can't change the structure of the json because it's a business constraint. I was thinking of copying my json data in another state, then add the keys ... and still didn't try this solution and don't know if it works. I will update this if it's the case.
Meanwhile, if someone had the same issue and has any idea/hint/suggestion, would appreciate very much. Thx.
I think the problem here is that the component is not rendering the data once you have it. This can be solved by using useState hook, you should lookup for the docs.
I would love to get a little bit more of the component that you are building. But the approach to this would be something like this:
const Component = () {
const [data, useData] = useState([]);
const onInputChange = (key, record, index) => (e) => {
e.preventDefault();
const data = // You get fetch the data here
useData(data);
};
return <>
{
data && data.itemsQ.map((item) => {
// here you display the information contained in each item
})
}
</>
}

JSX list of SharePoint list attachments not displaying when using map to render

I'm trying to display a list of attached file names using JSX/React/TypeScript.
Here's the function which is successfully retrieving the files. I'm storing them in a variable and also setting them into state (I've tried both ways by experimenting).
let theFiles = null;
const getAttachedFiles = async () => {
let item = await Utils.ReadListItem("MyList", Id);
item.attachmentFiles.get().then(v => {
theFiles = v.map(file => file.FileName);
console.log(theFiles, 'theFiles');
setAttachedFiles(theFiles);
console.log(attachedFiles, 'attachedFiles');
});
};
Here's the JSX:
<div>
{theFiles.map((file, index) =>
<li key={index}>{file}</li>)}
</div>
The list is not displaying at all. I've set the mapped list of items into state but because of async, it's not updating in time of render. Also setting the list of files to a variable doesn't work either.
UPDATE: I didn't mention i'm using TypeScript and this was the issue. Here is what I did for the benefit of anyone struggling with TypeScript like me:
const [attachedFiles, setAttachedFiles] = useState<Array<IAttachmentInfo>>(null);
...........
const getAttachedFiles = () => {
Utils
.ReadListItem("MyList", Id)
.then(item => {
item.attachmentFiles
.get()
.then(setAttachedFiles);
});
};
...........
{attachedFiles ? attachedFiles.map((attachedfile, index) =>
<li key={index}>
{attachedfile.FileName}
</li>
) : null}
I added the <Array> Type to the state. This solved the problem. The issue was I was retrieving a string[] into the theFiles variable and it was expecting something more specific given by the Type.

How to print a specific element of an array passed via context api?

I am trying to a print a specific element of an array based on the user, How do I get that specific element and print it on the screen ????
const state = useContext(GlobalState)
const[ulocations]=useState(state.categoriesAPI.locationapi[0])
const [userlist]=useState([{location_id:'5476',name:'John', age:36}])
// ulocations is an ARRAY OF OBJECTS [{...},{...},{...}]
// where an obj contains{_id:'5476',name:'europe'}
const findspecificcountry=()=>{
for(let i=0;i<ulocations.length;i++){
if(ulocations[i]._id==myuserlist[0].location_id){
return ulocations[i].name
}
}
}
return(
userlist.map(a=>{
<h1> a.name </h1>
<h2>a.age </h2>
<h3> {findspecificcountry()} </h3> // doesnt print the value europe ????? nothing appears
})
)
If you are trying to retrieve your locations from the GlobalState context, you would do so with:
const { state, dispatch } = useContext(GlobalState)
const ulocations = state.categoriesAPI.locationapi[0] // Assuming this is your location list
It looks like your user list should just be a constant here also. No need for the useState hook:
const userlist = [{location_id:'5476',name:'John', age:36}]
When you map over your userlist, you can then pass the user's location ID to your function:
userlist.map(a => {
...
<h3> {findspecificcountry(a.location_id)}</h3>
})
The function would then accept that location parameter:
const findspecificcountry = (id) => {}
I don't know the format of your API data, so I leave updating the function to you.

Access outside parameter in SetState function

I am not able to access onClick parameter inside setState function.
const [tableData, settableData] = useState({ tableDataList: [] });
const deleteRow = (rowId) => {
settableData(tData => {
//I have to access rowId to delete row with rowid from tData here
return tData;
});
}
.
.
//This button is inside a table. Present in all rows
<button className="btn-dark" onClick={() => deleteRow(rowId)}>DELETE</button>
Can any one help me to access rowId inside setState function?
You have to filter out using normal array methods from JavaScript. One example is the filter method that helps you filter the array based on how you like it to be filtered.
The following example will filter the array, returning all items, except for the item that matches the rowId, returning a new array without the deleted item:
tableData.tableDataList.filter(item => item.id !== rowId)
The full example must look something like this:
settableData(tData => {
return tData.tableDataList.filter(item => item.id !== rowId);
});

How to map async key to call API

I have 2 classes, App.js and Categories.js. the App.js called an API and managed to get the name of the categories and the ID of the category into JSON, the data is then pushed like so and gets transfered into a prop of class Category
Object.keys(data.categories).forEach((category,index) => {
categories.push(data.categories[index].name);
categoryIDs.push(data.categories[index].id)
})
<Categories
categoryName = { this.state.categoryName }
categoryID = { this.state.categoryID }
/>
Then in my Categories class, the data is returning a pair through a map button, and i used key to associate with the array values like a pair but I can't pass the values to help get the values needed to dynamically access the API
class Categories extends React.Component {
getResult= async () => {
const api_call = await fetch(`
http://callthisapi.com/v1/categories/items?format=json&category=1334134&apiKey=${API_KEY}`)
// Convert response to json
const data = await api_call.json();
console.log(data);
}
render() {
return (
<div>
<br />
{
this.props.categoryName.map
((name,i) => <button key={i} onClick={this.getResult}> {name} {this.props.categoryID[i]} </button>)
}
</div>
as you can see the 1334134 is a hard coded value right now but the number is currently associated in {this.props.categoryID[i]}. How do i allow the number to change dynamically? I tried to pass in the value through a parameter but everything broke afterwards.
The value that I want is in {this.props.categoryID[i]} and I can't extract it to the function is the tl;dr
Change your onClick to be onClick={() => this.getResult(this.props.categoryID[i])}.
Then getResult can accept a parameter: getResult = async (id) => { ... }
API call: http://callthisapi.com/v1/categories/items?format=json&category=${id}
See React documentation for passing functions: https://reactjs.org/docs/faq-functions.html

Resources