import React, { useEffect, useState } from 'react';
import Axios from 'axios';
const PictureOfTheDay = () => {
const [fetchedImage, setFetchedImage] = useState('');
const imageHandler = (name) => {
Axios.get(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_data=2015-6-3&sol=1000&camera${name}&api_key="MY_API_KEY"/`).then((res) => {
setFetchedImage(res.data.photos[0].img_src);
// console.log(res.data.photos.img_src);
}, []);
};
useEffect(() => {
imageHandler();
});
return (
<section>
<h3>Astronomy Picture Of The Day</h3>
<div className="picture">
<button onClick={() => imageHandler('FHAZ')}>FHAZ</button>
<button onClick={() => imageHandler('RHAZ')}>RHAZ</button>
<button onClick={() => imageHandler('MAST')}>MAST</button>
<button onClick={() => imageHandler('CHEMCAM')}>CHEMCAM</button>
</div>
<img src={fetchedImage} alt="" />
</section>
);
};
export default PictureOfTheDay;
Currently, I am doing something like this but it is just showing me one image I know I have done something stupid but please help me out.
Used dummy API.
https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=DEMO_KEY
The JSON response sample.
{
"id": 102693,
"sol": 1000,
"camera": {
"id": 20,
"name": "FHAZ",
"rover_id": 5,
"full_name": "Front Hazard Avoidance Camera"
},
"img_src": "http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/fcam/FLB_486265257EDR_F0481570FHAZ00323M_.JPG",
"earth_date": "2015-05-30",
"rover": {
"id": 5,
"name": "Curiosity",
"landing_date": "2012-08-06",
"launch_date": "2011-11-26",
"status": "active"
}
},
{
"id": 102694,
"sol": 1000,
...
"img_src": "http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/fcam/FRB_486265257EDR_F0481570FHAZ00323M_.JPG",
}
},
...
Store the data in a useState variable and then map it and show only the image URL[img_src]. Hope it will solve your problem in this way.
const [myData, setMyData] = useState([]);
useEffect(() => {
fetch("API...")
.then(res=>res.json())
.then(data=>setMyData(data));
}, [])
{
myData.map(myData =><ImageCompo
key={myData.id}
myData={myData}
></ImageCompo>)
}
In ImageCompo retrieve imag_src props:
function ImageCompo({myData}) {
const{id,img_src}=myData;
<img src={img_src} alt='' width={200} height={200}></img>
Hope it would help you.
Related
I am creating an e-commerce app where I am trying to apply filters e.g. filter by gender and/or brands. The filters only work individually and if I try to click both, the other filter cancels.
Please help! thank you in advance.
I am creating an e-commerce app where I am trying to apply filters e.g. filter by gender and/or brands. The filters only work individually and if I try to click both, the other filter cancels.
Please help! thank you in advance.
Sorry about the duplicate of question, Stackoverflow kept stopping me from posting because I have too much codes instead of description.
import React, { useState, useEffect } from 'react';
import './Clothing.css'
import data from '../../data/data2.json';
const Clothing = () => {
const [items, setItems] = useState([]);
const [color, setColor] = useState(null);
const types = [
{ id: 11, value: 'All' },
{ id: 22, value: 'Cap' },
{ id: 33, value: 'Sweatshirt' }
]
const genders = [
{ id: 55, value: 'Men' },
{ id: 66, value: 'Women' }
]
const brands = [
{ value: 'Graver' },
{ value: 'LMC' }
]
useEffect(() => {
setItems(data);
}, [])
const handleGender = (e) => {
const filteredItems = data.filter((d) => {
return d.gender === e.target.value
})
setItems(filteredItems)
}
const handleBrand = (e) => {
const filteredItems = data.filter((d) => {
return d.brand === e.target.value
})
setItems(filteredItems)
}
return (
<div className="bodyDiv">
<div className="leftMenu">
<div className='leftList'>
<h3>Gender</h3>
{
genders.map((g) =>
<button
id={g.id}
value={g.value}
onClick={(e) => {
handleGender(e);
handleColor(e);
}}
>{g.value}</button>
)
}
</div>
<div className='leftList'>
<h3>Brand</h3>
{
brands.map((b) =>
<button
id={b.id}
value={b.value}
onClick={(e) => {
handleBrand(e);
}}
>{b.value}</button>
)
}
</div>
<div className='itemSection'>
<div className='itemCount'>
Total {items.length}
</div>
<div className="itemLists">
{items.length === 0
? "No items found"
:
items.map((item) =>
<div className="itemCard" key={item.id}>
<img src={item.img} alt='clothes' />
<div className="itemText">
<h4>{item.brand}</h4>
<h4>{item.gender}</h4>
</div>
</div>
)}
</div>
</div>
</div>
)
}
export default Clothing
I have solved this problem. Message me if you need help.
I am using reacttable-6 to render the data in table,but the is not showing up in table.It is giving me "No data found".Data is coming from api,even i console logged the response from api,the what data i am getting from is fine.I aslo hard coded the data,then the data is showing up in the table
I am not able to figure out what the issue is.Thanks inadvance.
import React,{useState} from 'react'
import ReactTable from "react-table-6";
import 'react-table-6/react-table.css';
import axios from "axios";
export default function Inventory(){
var compdata = [
{
FirstName: "Chandu",
LastName: "Reddy",
_id: "63c5766f9d9de1b624481574",
Discription: {
_id: "63c5766f9d9de1b624481574",
DOB: "Havells",
Age: "HiBreak",
},
Address: "Something",
}
];
const handleDelete=(data)=>{
console.log(data)
}
const handleEdit=()=>{
console.log("dcdc")
}
const column = [
{
Header: "FirstName",
accessor: "FirstName",
sortable: false
},
{
Header: "LastName",
accessor: "LastName",
sortable: false
},
{
Header: "Address",
accessor: "Address",
sortable: false
},
{
Header: "Actions",
Cell: (row) => (
<div>
<a onClick={() => handleEdit(row.original)}>
Edit
</a>
<a onClick={() => handleDelete(row.original)}>
Delete
</a>
</div>
)
}
];
const [data1, setData1] = useState([]);
const [columns, setColumns] = useState(column);
const { toggle } = useContext(ThemeContext);
useEffect(()=>{
const fetch = async () => {
await axios
.get(`http://localhost:4001/api/uploadCsv/getData`)
.then((res) => {
setData1(res.data);
console.log(res.data)
});
};
fetch();
},[setData1]);
const [expanded, setExpanded] = useState({});
const onExpandedChange = (newExpanded) => {
setExpanded(newExpanded);
};
return(
<div className="container">
<div className='Table-container'>
<ReactTable
data={data1}
columns={columns}
defaultPageSize={data1.length}
showPagination={false}
resizable={false}
expanded={expanded}
// className="-striped -highlight"
getTrProps={(state, rowInfo, column, instance, expanded) => {
return rowInfo
? {
onClick: (expanded) => {
const newExpanded = { ...expanded };
newExpanded[rowInfo.viewIndex] = expanded[rowInfo.viewIndex]
? false
: true;
setExpanded(newExpanded);
}
}
: {};
}}
SubComponent={(row) => {
return (
<div style={{ padding: "20px" }}>
<em>{(row.original.Discription.Make)}</em>K <br />
</div>
);
}}
/>
<br />
</div>
</div>
)
}
Screen shot for reference
Change your useEffect like this and add another to check did data1 updated yet. Depend on data1 have value or not we will have different way to solve this
useEffect(() => {
axios.get(`http://localhost:4001/api/uploadCsv/getData`).then((res) => {
setData1(res.data);
});
}, []);
useEffect(()=>{
console.log(data1)
},[data1])
I have array of objects (items) with button clickHandler function. When you click on button, it should add that object to new array named ‘myNewArray’. Please help me to achieve this. I added demo object inside array ‘myNewArray’.
Explaination: If i click on category button '1-furniture', that object will added to new array named 'myNewArray'
import React, { useState } from "react";
const App = () => {
const [items, setItems] = useState([
{ name: "Furniture", categoryKey: 1 },
{ name: "Shoes", categoryKey: 2 },
{ name: "Electronics", categoryKey: 3 },
{ name: "Clothes", categoryKey: 4 },
{ name: "Grocery", categoryKey: 5 },
]);
const [myNewArray, setMyNewArray] = useState([{ name: "demo-item", categoryKey: 100 }]);
const clickHandler = (categoryKey: any) => {
console.log(categoryKey);
};
return (
<div>
{items.map((item) => (
<button onClick={() => clickHandler(item.categoryKey)} key={item.categoryKey}>
{item.categoryKey}-{item.name}
</button>
))}
<h4>New array after clicking on item from above array[items]</h4>
{myNewArray.map((item) => (
<button onClick={() => clickHandler(item.categoryKey)} key={item.categoryKey}>
{item.categoryKey}-{item.name}
</button>
))}
</div>
);
};
export default App;
just use set method in the useState
const clickHandler = (item: any) => {
setMyNewArray(prev => [...prev, {name:item.name,categoryKey: item.categoryKey}])
};
and pass item in the click
onClick={() => clickHandler(item)}
Here's the working solution:
import React, { useState, useEffect } from "react";
const App = () => {
const [items, setItems] = useState([
{ name: "Furniture", categoryKey: 1 },
{ name: "Shoes", categoryKey: 2 },
{ name: "Electronics", categoryKey: 3 },
{ name: "Clothes", categoryKey: 4 },
{ name: "Grocery", categoryKey: 5 }
]);
const [myNewArray, setMyNewArray] = useState([
{ name: "demo-item", categoryKey: 100 }
]);
useEffect(() => {
console.log(myNewArray);
}, [myNewArray]);
const clickHandler = (item) => {
setMyNewArray([...myNewArray, item]);
};
return (
<div>
{items.map((item) => (
<button onClick={() => clickHandler(item)} key={item.categoryKey}>
{item.categoryKey}-{item.name}
</button>
))}
<h4>New array after clicking on item from above array[items]</h4>
{myNewArray.map((item, i) => (
<button key={i}>
{item.categoryKey}-{item.name}
</button>
))}
</div>
);
};
export default App;
The live demo is here: https://codesandbox.io/s/determined-solomon-phyy9u?file=/src/App.js:0-1163
You can have a look at the console to check the myNewArray updates.
You could also do like this.
if Item is with the matching category Key. Then, it's Update the myNewArray state with the new item
const clickHandler = (categoryKey: any) => {
const item = items.find((i) => i.categoryKey === categoryKey);
setMyNewArray([...myNewArray, item]);
};
Here is Codesandbox
I'm trying to get specific values from an array object returned by my node.js api
Here's the array of object returned by my node.js api
[
{
"name": "device1",
"serial": "WMD105222022",
"status": "online"
},
{
"name": "device2q",
"serial": "sdfsdf",
"status": "online"
},
{
"name": "ducs",
"serial": "WMD105222022",
"status": "online"
}
]
Here's my react.js code
import React, {useState, useEffect} from "react";
import './Module.css';
import {SDH} from '../../components';
import {temp, water, humidity, nutrient} from '../../assets';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import Form from 'react-bootstrap/Form';
import {Link} from 'react-router-dom';
import Axios from "axios";
const Module = () => {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const email = sessionStorage.getItem("email");
const [device, setDevice] = useState({});
Axios.defaults.withCredentials = true;
useEffect(() => {
Axios.get("http://localhost:3020/getdevice", {
params: {
email: email
}
})
.then((response) => {
setDevice(response.data);
})
// .then((response) => {},
// (err) => {
// alert("No Data To Show");
// }
// )
.catch((err) => {
return false;
});
},[]);
const DisplayData = () => {
return (
<div>
<td>{device.name}</td>
<td>{device.serial}</td>
<td>{device.status}</td>
</div>
);
};
return (
<div className="MainBodyM">
<SDH/>
<h3 className="deviceStatus"></h3>
{/* <Button onClick={getDevices} variant="primary" type="submit">Refresh List</Button> */}
<div className="tempHeader">
<table>
<tr>
<td>Name</td>
<td>Serial Number</td>
<td>Status</td>
</tr>
<tr>
{DisplayData}
</tr>
</table>
</div>
<Link to="/registerdevice">
<Button>Add Control Module</Button>
</Link>
</div>
);
};
export default Module;
I needed to get the name, serial, and status to be displayed in a table. up until now i'm still getting nowhere, please help, i'm only using {JSON.stringify(device, null, 3)} to display the returned array of object that's why i know i'm getting an array of object. I'm open to suggestions and correction. Thank you.
I need the output to be like this, regardless how many devices/data i add in array of object.
Device Serial Status
Device1 121 online
device2 234135 offline
balcony ash3 online
bathroom dsgfkahaskj23 online
so on... tj2l5 offline
You must send an array from the backend. You must send a JSON
In express
app.get("/test", (req, res) => {
res.json({
array: [
{
name: "device1",
serial: "WMD105222022",
status: "online",
},
{
name: "device2q",
serial: "sdfsdf",
status: "online",
},
{
name: "ducs",
serial: "WMD105222022",
status: "online",
},
],
});
});
Note that I send a JSON, not an array
In React:
const [data, setData] = useState([]);
useEffect(() => {
var config = {
method: "get",
url: "http://localhost:3000/test",
headers: {},
};
axios(config)
.then(function (response) {
const data = JSON.stringify(response.data);
const array = JSON.parse(data).array;
setData(array);
})
.catch(function (error) {
console.log(error);
});
}, []);
Note that I convert the JSON to an object to be able to iterate it
the return on the component
<table>
{data &&
data.map((row, key) => {
return (
<tr key={key} style={{ color: "red" }}>
<td>{row.name}</td>
<td>{row.serial}</td>
<td>{row.status}</td>
</tr>
);
})}
</table>
You can extract the columns name, ie. "Device", "Serial", "Status", into an array, and iterate over them using map function:
const [data, setDate] = useState();
const columns = ["Device", "Serial", "Status"]; // hard code the columns
const lookUpDataKey = {
Device: "name",
Serial: "serial",
Status: "status"
};
useEffect(() => {
setDate(dataFromApi); // mimic getting data from api
}, []);
if (!data) return <div>loading</div>;
return (
<div className="App">
<div style={{ display: "flex" }}>
{columns.map((column, columnIndex) => (
<div key={columnIndex}>
{/* Column name */}
<div>{columns[columnIndex]}</div>
{/* Column data */}
{data.map((item, dataIndex) => (
<div key={dataIndex}>
<div>{item[lookUpDataKey[column]]}</div>
</div>
))}
</div>
))}
</div>
</div>
);
Notice we use a lookUpDataKey object for matching column's name to the corresponding object key.
Try it out in updated sandbox.
I am using ReactJs with Laravel as an API. I Want to display some data but nothing worked for me.
This is the result of the API:
{
"user_id": 2,
"id": 1,
"chat": [
{
"sender_id": 3,
"message": "Hi"
},
{
"sender_id": 4,
"message": "Hello"
}
]
}
When I try to display user_id, it displayed it but the other part, the chat, didn't show up.
This is how I consume the API:
const [chatsData, setChats] = useState([]);
// ** Renders Chat
useEffect(() => {
getChats()
}, []);
const getChats = async () => {
const response = await axios.get(`${API_ENDPOINT}/api/listChats`);
setChats(response.data);
}
<ul className='chat-users-list chat-list media-list'>
{chatsData.map((item) => {
return (
<>
<Avatar img={item?.senders?.user_image} imgHeight='42' imgWidth='42' />
<li><h5>{item.chat?.message}</h5></li>
</>
)
})}
</ul>
I will be very thankful if anyone could help me.
You just have to loop on the chat field like:
import React from 'react';
export default function App() {
const response = {
user_id: 2,
id: 1,
chat: [
{
sender_id: 3,
message: 'Hi',
},
{
sender_id: 4,
message: 'Hello',
},
],
};
return (
<div>
<ul className="chat-users-list chat-list media-list">
{response.chat?.map((item) => {
return (
<>
<li>
<h5>
{item.sender_id} : {item?.message}
</h5>
</li>
</>
);
})}
</ul>
</div>
);
}
Code example here