'ReactJS and Azure library problem with displaying certain elements
so I'm doing a school project where I'm trying to fetch data from my Azure blob-storage and then displaying it on a website which is creating in ReactJS. I've managed to fetch the pictures from my storage and they render fine, but when I try to render the "createdOn prop" nothing is being shown.
I just wanna add that I'm fairly new to javascript so my code might look like garbage.
The BodyPresenter function is the one that connects to my blob storage and then retrieves the data. It works without a problem for the "blobImages" but won't work for the "blobDateTime"
function BodyPresenter() {
const [blobImages, setBlobImages] = useState([]);
const [blobDateTime, setBlobDateTime] = useState([]);
const account = "ktodb";
const containerName = "images";
useEffect(() => {
async function blobStorage() {
const blobServiceClient = new BlobServiceClient(api_client.get_blob_account(account));
const containerClient = blobServiceClient.getContainerClient(containerName);
let blobs = containerClient.listBlobsFlat();
let newArrayForImages = [];
let newArrayforDates = [];
for await (const blob of blobs) {
// console.log(`${blob.name}`); //`Blob ${i++}:
newArrayForImages.push(blob.name);
newArrayforDates.push(blob.properties.createdOn)
}
setBlobImages(newArrayForImages);
setBlobDateTime(newArrayforDates);
}
return blobStorage;
}, [blobImages])
console.log(blobDateTime)
As you can see I console.log() the blobDateTime at the bottom and it gives me the data I want in the console, aka the creation data of all my images: image of console
Then I try to render the data in a view file and I guess the problem lies here, but I'm sure what the problem is and how to fix it, to remind you I'm a new to javascript. The images are being rendered but not the DateTime
function BodyView( {blobImages, blobDateTime} ) {
console.log(blobDateTime)
return (
<div>
{blobImages.map( (blobImages, blobDateTime) => (
<div>
<div className="images">
<img
key={blobImages.id}
src={api_client.get_image_url(blobImages)}
alt=""
/>
</div>
<div>{blobDateTime}</div>
</div>
))}
</div>
)
}
Solution 1:[1]
Use
componentDidMount
to load data, then store it in the state.Sample code,
componentDidMount() {
// Runs after the first render() lifecycle
}
- Then retrieve and use it in render call.
render() {
return (
<div>{YourDateTime}</div>
);
}
Some of the useful links here,
- Complete information on React componentDidMount.
- Fetch and Display Data from API in React JS check here.
- How to fetch data in React check here.
- Similar issue fixed here with the help of componentDidMount.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | RajkumarPalnati-MT |