How to use selected value in React dropdown as api url id? - javascript

I want to render into table specific data from url with id taken after user select the needed value so here is my code:
fetching data for select options:
export default function Dashboard() {
const [value, setValue] = useState();
const [students, setstudents] = useState([]);
useEffect(() => {
const fetchStudents = async () => {
try {
const resp = await Axios({
method: "GET",
url: "https://jsonplaceholder.typicode.com/users",
headers: {
"Content-Type": "application/json",
},
});
setstudents(resp.data);
} catch (err) {}
};
fetchStudents();
}, []);
const classes = useStyles();
const [selected,setselected]=useState();
const options = students.map(s => ({
"value" : s.id,
"label" : s.username
}))
const handleChange = (event) => {
setselected(event.value);
};
now fetching data in dashboard function for selected value:
const [tabl, settabl] = useState([]);
useEffect(() => {
const fetchtabl = async () => {
try {
const resp = await Axios({
method: "GET",
url: "https://jsonplaceholder.typicode.com/users"+{selected},
headers: {
"Content-Type": "application/json",
},
});
settabl(resp.data.surveys);
} catch (err) {
console.log(err);
}
};
fetchtabl();
}, []);
const getTableData = (tabl) => {
return tabl.map((tab) => [
tab.id,
tab.name,
tab.username,
]);
};
now render data in return:
Select the course:
<Select options={options} onChange={handleChange}/>
<Table
tableHead={["Course Code", "Course Name", "Survey Link"]}
tableData={getTableData(tabl)}
tableHeaderColor="primary"
/>
but nothing appear after select the value needed how can i fix it and does react allow to use selected value like this?
data
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan#yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
},
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
},

So based on the conversation in the comment section the value is there in selected. Then the only problem is useEffect is not triggered on change because of empty dependency array.
I suggest few modifications in your code:
Add to the dependency array selected as [selected] which will trigger the function once you have change on that state.
Check for null or undefined values in order not to concatenate without value.
Also I added one extra slash into your URL after users so now it's users/.
So the URL would be at the end of the day:
`https://jsonplaceholder.typicode.com/users/${selected}`
Based on the explanation try as:
useEffect(() => {
const fetchtabl = async () => {
try {
const resp = await Axios({
method: "GET",
url: `https://jsonplaceholder.typicode.com/users/${selected}`,
headers: {
"Content-Type": "application/json",
},
});
settabl(resp.data.surveys);
} catch (err) {
console.log(err);
}
};
if (selected) {
fetchtabl();
}
}, [selected]);
+1 suggestion:
Maybe it's not related but you have in .map() an extra [] which might be not needed, so try as:
const getTableData = (tabl) => {
return tabl.map((tab) => ({
tab.id,
tab.name,
tab.username,
}));
};
In this way .map() will return an array of objects with the properties of id, name, username.

Related

React table from object with objects

I got 2 types of json API and i want to display them in table. First one has following structure:
data1:[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address":"Gwenborough",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": "Romaguera-Crona"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": "Wisokyburgh",
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": "Deckow-Crist"
}
]
Second:
data2:[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
}
]
My Table component works for first type of data (data1) and creates a table. But obviously for second (data2) type i'm getting error. I tried a lot of things and i can't get access to address and geo fields and can't display them in table.
Table component:
export default class Table extends React.Component {
constructor(props){
super(props);
this.getHeader = this.getHeader.bind(this);
this.getRowsData = this.getRowsData.bind(this);
this.getKeys = this.getKeys.bind(this);
}
getKeys = function(){
return Object.keys(this.props.data[0]);
}
getHeader = function(){
var keys = this.getKeys();
return keys.map((key, index)=>{
return <th key={key}>{key.toUpperCase()}</th>
})
}
getRowsData = function(){
var items = this.props.data;
var keys = this.getKeys();
return items.map((row, index)=>{
return <tr key={index}><RenderRow key={index} data={row} keys={keys}/></tr>
})
}
render() {
console.log('Get keys:', this.getKeys());
return (
<div>
<table>
<thead>
<tr>{this.getHeader()}</tr>
</thead>
<tbody>
{this.getRowsData()}
</tbody>
</table>
</div>
);
}
}
const RenderRow = (props) =>{
return props.keys.map((key, index)=>{
return <td key={props.data[key]}>{props.data[key]}</td>
})
}
const uniqueArr = [...data1, ...data2]
const formatData = uniqueArr.map((item) => {
if(typeof item.address === "object"){
return {
...item,
address: item.address.street.concat(", ", item.address.city),
company: item.company ? item.company.name : ""
}
}
return item
})

Reading JSON data with axios and React

So I created this backend json response.
{
"places": [
{
"location": {
"lat": 40.3714624,
"lng": 21.7614661
},
"_id": "5f9bb2ff4fc07350c317500c",
"title": "Alcazar Park",
"description": "A lovely park.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
"creator": "5f9bb2ee4fc07350c317500b",
"__v": 0,
"id": "5f9bb2ff4fc07350c317500c"
},
{
"location": {
"lat": 40.3714624,
"lng": 21.7614661
},
"_id": "5f9bb4f9d92cd5541f5922fc",
"title": "Alcazar Park",
"description": "A beautiful park.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
"creator": "5f9bb2ee4fc07350c317500b",
"__v": 0,
"id": "5f9bb4f9d92cd5541f5922fc"
},
{
"location": {
"lat": 40.3714624,
"lng": 21.7614661
},
"_id": "5f9bb632d92cd5541f5922fd",
"title": "Train station of Larisa",
"description": "An old but cool train station",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
"creator": "5f9bb2ee4fc07350c317500b",
"__v": 0,
"id": "5f9bb632d92cd5541f5922fd"
}
]
}
Now I want to display in a list just the title of each place in the array. Here is my code
for that in React
const DataFetching = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios
.get('http://localhost:5000/api/places/user/5f9bb2ee4fc07350c317500b')
.then(res => {
console.log(res)
setPosts(res.data);
})
.catch((err) => {
console.log(err)
})
}, []);
return(
<div>
<ul>
{
posts.map(post => <li key={post.id}>{post.title}</li>)
}
</ul>
</div>
)
}
export default DataFetching;
However, I am getting this error
How can I fix it?
TypeError: posts.map is not a function
Thanks,
Theo
Try this:
setPosts(res.data.places)
posts?.map(post => <li key={post.id}>{post.title}
or:
setPosts(res.data)
posts.places?.map(post => <li key={post.id}>{post.title}

How to get a specific data from fetch api

I am trying to get and show a specific data from api in a <Text> tag in my React Native app.
What I'm trying to do is to show the name of second object from that api.
Here is my code :
class HomeSreen extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
};
}
componentDidMount() {
const request = new Request('http://jsonplaceholder.typicode.com/users');
fetch(request)
.then(response => response.json())
.then(responseJson => {
this.setState({
dataSource: responseJson,
});
});
}
render() {
return (
<View>
<Text>Home Screen</Text>
<Text>{this.state.dataSource[1].name}</Text>
</View>
);
}
}
And the API :
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
.
.
.
But I can't get the data I need.
Any help would be appreciated
these data requests asynchronously, so when the first render occurs, there is no data returned from the API.
class HomeSreen extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
};
}
componentDidMount() {
const request = new Request('http://jsonplaceholder.typicode.com/users');
fetch(request)
.then(response => response.json())
.then(responseJson => {
this.setState({
dataSource: responseJson,
});
});
}
render() {
return (
<View>
<Text>Home Screen</Text>
{
this.state.dataSource.length === 0 ?
<Text>Waiting moment.</Text> :
<Text>{this.state.dataSource[1].name}</Text>
}
</View>
);
}
}
Making these changes you can visualize the data you need.
If the problem is that your component isn't updating the that property after the request is complete it is because you are doing a 'shallow merge' on the dataSource Array so React isn't able to detect changes to the data. There are a few ways you can handle it:
Deep merge
fetch(request)
.then(response => response.json())
.then(responseJson => {
this.setState(prevState => {
return {
...prevState.dataSource,
dataSource: responseJson.map((obj, i)=>{ return {...dataSource[i], ...obj}},
}
});
});
https://reactjs.org/docs/optimizing-performance.html#shouldcomponentupdate-in-action
Pull the name property out to the top-level of you component state
class HomeSreen extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
screenTitle
};
}
componentDidMount() {
const request = new Request('http://jsonplaceholder.typicode.com/users');
fetch(request)
.then(response => response.json())
.then(responseJson => {
this.setState({
screenTitle: responseJson[1].name,
});
});
}
render() {
return (
<View>
<Text>Home Screen</Text>
<Text>{this.state.screenTitle}</Text>
</View>
);
}
}

Not getting the expected response from Backend in web service

I wrote an api call in AngularJS to get data from backend JAVA
Here is my code
$scope.memberForm = {};
$scope.memberForm.member_address = {};
$scope.memberRegForm = function() {
$scope.btnloading = true;
$('#add-btn').prop('disabled', true);
url = '/member/add';
var request = $http({
method: "post",
url: url,
data: angular.toJson($scope.memberForm),
headers: {
'Content-Type': 'application/json'
},
});
}
But I am not getting desire response from backed, Response that's I am actually getting from backend is
{
"fullname":"sdfgsdf",
"fathername":"sdfsdf",
"email":"sdfsdf#gmail.com",
"date_of_birth":"1993-03-24",
"admission_date":"2018-10-22",
"phoneno":"0987654321",
"nationality":"United States",
"member_address":
{
"address":"5 meadow st",
"state":"Connecticut",
"zipcode":"06770",
"district":"zc"
},
"college":"cvbcv",
"qualification":"bcvbcv",
"slno_ivpr":"12"
}
But here is my desire response. I need member_address as an array of ojects instead of a single object
{
"fullname": "avinash",
"fathername": "xxxxxxx",
"date_of_birth": "1991-08-08",
"nationality": "indian",
"admission_date": "2015-08-08",
"college": "ABC college",
"slno_ivpr": null,
"phoneno": "1234567890",
"email": "avinash.mitresource#gmail.com",
"remarks": "no remarks",
"member_renewal": [],
"qualification": "MCA",
"member_address": [
{
"address": "piratlanka,repalle",
"state": "AP",
"district": "Guntur",
"zipcode": "522264",
"type": "PermanentAddress"
},
{
"address": "padamata",
"state": "AP",
"district": "vijayawada",
"zipcode": "522201",
"type": "ResidencialAddress"
}
]
}

trying to add user to database js

this code is used to add user to database
export const addUserInDB = (userEntityModel: UserEntityModel) => {
userEntityModel.id = '7';
return fetch(usersUrl, {
method: 'POST',
body: JSON.stringify(userEntityModel),
}).then((res) => res.json());
};
but it only returns this code in the database
{
"id": "Tcvpety"
}
And i want something like this
{
"id": "5",
"login": "luigi",
"password": "luigi125",
"email": "lluis.rubies#test.com",
"country": "Japan",
"type": "Customer",
"language": [
"Japanese",
"English"
]
},

Categories