Blob list is not updating in react js component - javascript

I have two components,
Uploader Component
Which uploads the file to Azure storage
ContainerList Component
Which fetches the uploaded file's data from Azure storage.
For fetching data from azure and show in ContainerList, I referred to ListBlobs in (https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-blob.html)
My components are completely independent components that were imported in a different react project by using npm-link. For npm link, I referred to this documentation (https://60devs.com/simple-way-to-manage-local-node-module-using-npm-link.html)
import {Uploader, ContainerList} from 'blobuploader';
import React from 'react';
class App extends React.Component{
render(){
return (
<Uploader
accountName={azureCredentials.accountName}
sasToken={azureCredentials.sasToken}
multiple={true}/>
<ContainerList
accountName={azureCredentials.accountName}
sasToken={azureCredentials.sasToken} />
);
}
}
The main issue is when I uploaded files to Azure storage by using the Uploader Component. Container List is not updating i.e the newly uploaded file to azure storage is not reflected in ContainerList. Need to reload the page for seeing updated data in ContainerList.
For example, you can see below the image where a new file has been uploaded but not showing in the list(i.e ContainerList)
Please help me to resolve this issue.
Thanks in advance
ContainerList code
import React from 'react';
import '../css/containerList.css';
import axios from 'axios';
import PROGRESS from '../assets/progress.svg'
import PropTypes from 'prop-types';
class ContainerList extends React.Component{
constructor(props){
super(props);
this.state= {
datas: [],
};
this.blobService = null;
this.initConnections.bind(this);
}
componentDidMount(){
const script = document.createElement('script');
script.src = "https://dmrelease.blob.core.windows.net/azurestoragejssample/bundle/azure-storage.blob.js";
script.async = true;
document.body.appendChild(script);
script.onload = () => {
this.initConnections();
};
console.log('script ended');
}
initConnections = () => {
var accountName = this.props.accountName;
var SasToken = this.props.sasToken;
var blobUri = 'https://' + accountName + '.blob.core.windows.net';
this.blobService = this.blobService === null ? AzureStorage.Blob.createBlobServiceWithSas(blobUri, SasToken) : this.blobService;
this.blobService.getServiceProperties({options: ['clientRequestId']}, (error, result)=>{
if(error){
console.log('Error Creating Blob Service..')
console.log(error);
} else {
this.blobService.listBlobsSegmented('my-con', null, {include:["metadata"]}, (error, results) => {
if (error) {
console.log(error);
}
else {
var temp =[]
results.entries.map(async (ele,index) => {
console.log('Tag',ele);
var val = index+1;
var type = ele.contentSettings.contentType;
temp.push({number:val,name:ele.name,type,status:<button className='container-button'>PASS</button>,email:"testtagcheck123456#gmail.com",apiStatus:PROGRESS});
if(results.entries.length === temp.length){
this.setState({datas:temp});
}
});
}
});
}
});
}
render(){
//SHOWING DATA IN UI LIST FROM this.state.datas
return (
<div className= "table-box">
<div className="table-row-head">
{
(["No","File-Name","Type","Status","Outlook-Mail","API-Status"]).map((ele => {
return( ele === "No" ?<div className="table-cell table-head first-cell" style={{width:'4%'}}>
<p className ="heading-label">{ ele} </p>
</div> : <div className="table-cell table-head" style={{width:'20%'}}>
<p className="heading-label">{ ele} </p>
</div>)
}))
}
</div>
{
this.state.datas.map( (eles,index) => {
return (
<div className='table-row' key={index}>
<div className="table-cell first-cell" style={{width:'4%'}}>
<p>{ eles.number} </p>
</div>
<div className="table-cell" style={{width:'23%'}} >
<p>{eles.name} </p>
</div>
<div className="table-cell" style={{width:'20%'}} >
<p >{eles.type} </p>
</div>
<div className="table-cell" style={{width:'15%'}} >
<p>{eles.status} </p>
</div>
<div className="table-cell" style={{width:'23%'}}>
<p>{eles.email} </p>
</div>
<div className="table-cell" style={{width:'15%'}}>
<img src={eles.apiStatus} alt="PROGRESS" style={{width:'30%',}}/>
</div>
</div>
);
}
)
}
</div>
);
}
}
ContainerList.propTypes = {
accountName: PropTypes.string,
sasToken: PropTypes.string,
}
export default ContainerList;

Related

React.js doesn't display fetched image from Django

My component successfully fetches info (texts and images) from the Django backend but fails to display the images.
related: react.js doesn't display fetched image
I removed file 192png from manifest.js and HTML and it didn't work so I put them back again as advised.
import React, { useState, useEffect, Fragment} from 'react';
import axios from 'axios';
import Carousel from 'react-elastic-carousel';
import './Schools.css';
import Test from '../assets/images/back.jpg';
const schoolBreakPoints = [
{width: 1, itemsToShow: 1 },
{width: 550, itemsToShow: 2 },
{width: 768, itemsToShow: 3 },
{width: 1200, itemsToShow: 4 },
];
function Schools() {
const [languageCenters, setLanguageCenters] = useState ([]);
useEffect(() => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const getLanguageCenters = async () => {
try {
const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/partners/list/`, config);
setLanguageCenters(res.data);
}
catch (err) {
}
};
getLanguageCenters();
}, []);
const getAllLanguageCenters = () => {
let allLanguageCenters = [];
let results = [];
languageCenters.map(languageCenter => {
console.log(languageCenter.photo)
return allLanguageCenters.push(
<Fragment key={languageCenter.id}>
<div className='school__display'>
<img className='school__display__image' src={languageCenter.photo} alt='school logo' />
</div>
<h3 className='school__language__center'>{languageCenter.name}</h3>
<p className='school__course'>{languageCenter.country}</p>
<p className='school__course'>{languageCenter.language}</p>
<p className='school__course'>{languageCenter.course}</p>
<p className='school__about'>{languageCenter.note}</p>
</Fragment>
);
});
for (let i = 0; i < languageCenters.length; i += 20) {
results.push(
<div key={i} className='school__card__row'>
<Carousel breakPoints={schoolBreakPoints}>
<div className='school__card'>
{allLanguageCenters[i]}
</div>
<div className='school__card'>
{allLanguageCenters[i+1] ? allLanguageCenters[i+1] : null}
</div>
<div className='school__card'>
{allLanguageCenters[i+2] ? allLanguageCenters[i+2] : null}
</div>
<div className='school__card'>
{allLanguageCenters[i+3] ? allLanguageCenters[i+3] : null}
</div>
<div className='school__card'>
{allLanguageCenters[i+4] ? allLanguageCenters[i+4] : null}
</div>
</Carousel>
</div>
);
}
return results;
};
return (
<div className='schools'>
<section className='schools__language__centers'>
<div className='schools__row'>
<h2 className='schools__subheading'>Language Centers</h2>
</div>
{getAllLanguageCenters()}
</section>
</div>
)
}
export default Schools
developer tool > all ;
developer tool > img ;
And below is what I see on the browser, only the broken icon and the rel ;
I managed to find a walk-around, when I use the build folder in Django through Django-server, the images are appearing perfectly. It's ok for me because I'm building a Django project but it's annoying why React can't display them.

react upload multiple files

I am trying to get my form to upload several files, but once I upload the first one, I have no chance to load a second one. Any Idea what I am doing wrong?
This is my upload component:
import React, { Component } from 'react'
import * as RB from 'react-bootstrap'
import Button from 'components/Button/Button'
class uploadMob extends Component {
constructor(props) {
super(props)
this.state = {
files: [],
}
}
onFilesAdded = (e) => {
const filesArray = this.state.files
filesArray.push(e.target.files[0])
this.setState({ files: filesArray })
this.uploadFiles()
}
async uploadFiles() {
this.state.files.forEach((file) => {
this.sendRequest(file)
})
}
sendRequest(file) {
const { pdfUploadToState } = this.props
pdfUploadToState(file)
}
render() {
const files = this.state.files
return (
<RB.Form.Group>
<div className="upload-btn-wrapper">
<div className="Files">
{files.map((file, key) => {
return (
<div key={key} className="Row">
<span className="Filename">
{file.name}
</span>
</div>
)
})}
</div>
<Button size="sm" variant="light">
Dateien hochladen
</Button>
<input
type="file"
name="files"
id="files"
onChange={(e) => {
this.onFilesAdded(e)
}}
multiple
/>
</div>
</RB.Form.Group>
)
}
}
export default uploadMob
The first file is uploaded perfectly, but as mentioned, the button does not respond when trying to upload a second one.
Thanks for the help!
Your code seems correct but when you use input type file with multiple attribute you need to select multiple files and then hit upload button insted of selecting files one by one.
also replace
filesArray.push(e.target.files[0])
with
for (var i = 0; i < files.length; i++)
{
filesArray.push(e.target.files[i]);
}
to upload file one by one
replace
onFilesAdded = (e) =>
{
this.state.files.push(e.target.files[0])
this.uploadFiles()
}
hope this will help you

How to make my object methods globally accessible

I'm working on a voip project. I have 2 pages, one page is for making outgoing calls, the other page is only for receiving calls.
Im using an external js file where I define a few object methods so I can access them everywhere in my component.
Problems:
I'm using the same file for both receiving calls and making
outgoing calls.(My object methods should do different things based on
the type of call)
I have to manipulate my HTML using javascript from within that object.
What I want:
I would like to have my object methods globally accessible from
within my component.
Able to manipulate the state within my object methods so I could re-render
My external js file (My voip client will call these listeners automatically)
var callListeners = {
onCallProgressing: function (call) {
audioProgress.src = './style/ringback.wav';
audioProgress.loop = true;
audioProgress.play();
//Report call stats
$('div#callLog').append('<div id="stats">Ringing...</div>');
},
onCallEstablished: function (call) {
audioIncoming.srcObject = call.incomingStream;
audioIncoming.play();
audioProgress.pause();
audioRingTone.pause();
//Report call stats
var callDetails = call.getDetails();
$('div#callLog').append('<div id="stats">Answered at: ' + (callDetails.establishedTime && new Date(callDetails.establishedTime)) + '</div>');
},
onCallEnded: function (call) {
audioProgress.pause();
audioRingTone.pause();
audioIncoming.srcObject = null;
if($('button#takeCall')) {
$('button#takeCall').addClass('d-none');
$('button#refuseCall').addClass('d-none');
}
//Report call stats
var callDetails = call.getDetails();
$('div#callLog').append('<div id="stats">End cause: ' + call.getEndCause() + '</div>');
if (call.error) {
$('div#callLog').append('<div id="stats">Failure message: ' + call.error.message + '</div>');
}
}
}
My component
class Recipient extends Component {
constructor() {
super()
this.state = {
name: null,
user: 'a User',
}
}
componentDidMount() {
this.CreateAccount();
}
CreateAccount() {
const name = this.state.user;
axios
.post("/api/auth", { name })
.then(res => { sinchClient.start(res.data).then(() => this.handleSuccess()); })
.catch((error) => { console.log(error) });
}
answerCall(e) {
e.preventDefault();
call.answer();
console.log(callListeners);
}
hangUpCall(e) {
e.preventDefault();
call && call.hangup();
console.log(call.getDetails());
}
handleSuccess() {
console.log('ready to receive incoming calls!')
}
renderCallArea() {
let callArea;
callArea =
<div className="frame">
<div id="call">
<form id="newCall">
<button id="takeCall" className="ml-2 btn btn-light d-none" onClick={(e) => this.answerCall(e)}>Opnemen</button>
<button id="refuseCall" className="ml-2 btn btn-dark d-none" onClick={(e) => this.hangUpCall(e)}>Weigeren</button>
<button id="leaveCall" className="ml-2 btn btn-dark d-none" onClick={(e) => this.hangUpCall(e)}>Verlaat gesprek</button>
{/* <button id="answer" onClick={(e) => this.answerCall(e)}>Answer</button> */}
</form>
</div>
<div className="clearfix"></div>
<div id="callLog">
</div>
<div className="error">
</div>
</div>;
return callArea;
}
render() {
const wrapperStyle = {
backgroundColor: 'rgba(127, 130, 160)',
minHeight: '600px',
}
const jumboStyle = {
backgroundColor: 'rgba(109, 113, 152)',
color: 'white',
borderRadius: '0'
}
return (
<div className="wrapper" style={wrapperStyle}>
<div className="jumbotron" style={jumboStyle}>
<h1 className="text-center">Wachten op een gesprek...</h1>
</div>
<div className='container mt-2'>
{this.renderCallArea()}
</div>
</div>
)
}
}
export default Recipient;
Any tips on how I should achieve this?
I don't 100% know what you mean by external js file, but I would extract that into your react app as an import. This is what it would look like:
import React, { Component } from 'react';
import './App.css';
class External {
static onCallProgressing () {
// Do some action...
return <div>{ `Ringing...` }</div>
}
}
class App extends Component {
callExternal() {
return External.onCallProgressing()
}
render() {
return (
<div className="App">
{ this.callExternal() }
</div>
);
}
}
export default App;
If you need to pass the value of the function to the child:
You first declare a state:
state = {
data
}
Set the state after calling the external function
callExternal() {
this.setState({ data: External.onCallProgressing() })
}
Have the child receive props from the state:
render() {
return (
<div className="App">
<MyChild data={ this.state.data } />
</div>
);
}
Have the child render the props:
render() {
return (
<div>
{ this.props.data }
</div>
);
}

onChange event is not triggering in Mozilla and IE React js/Redux

I am pretty new guy to react js.I am little bit confused why input type=file action is not working in Mozilla and IE it is working fine in Chrome.I don't why it is not working...Haaa that is pretty hard to find my mistake.I know this might be a simple noobie Mistake
Pls help me
import React from 'react';
import {connect} from 'react-redux';
import uuid from 'node-uuid'
import * as headerAction from '../../Actions/headerActions';
import * as uploadActions from '../../Actions/uploadActions';
import * as notificationActions from '../../Actions/notificationActions';
import shortid from 'shortid'
class Header extends React.Component{
static contextTypes = {
router:React.PropTypes.object
};
constructor(props){
super(props);
this.Hovered = this.Hovered.bind(this);
this.UnHovered = this.UnHovered.bind(this);
}
UnHovered(){
this.props.toggleMenu(false);
}
uniqueNameAndId(){
return uuid.v1().replace(/-/g, '');
}
//below function not triggered When onChange Event happen But file upload popsup
handleFileUpload(e){
//Not working
e.preventDefault();
this.props.setMainPostId(shortid.generate())
//Upload for single File not working
const reader = new FileReader();
//const file = e.target.files;
//console.log(file.length);
reader.onload = () => {
console.log("Hello",file.name)
};
let file = e.target.files[0];
reader.readAsDataURL(file);
//Upload for Multiple files NOt working
{/*if(file.length <= 5){*/}
{/*for(let i=0;i<file.length;i++){*/}
// const Reader = new FileReader();
// Reader.onload = () => {
// let pushData = {
// postOwnerUsername:null,
// id:this.uniqueNameAndId(),
// name:this.uniqueNameAndId(),
// caption:null,
// blobData:Reader.result
// };
// console.log(pushData)
// this.props.pushtoReducer(pushData)
// };
// Reader.readAsDataURL(file[i])
// }
// this.props.removeUploadMenu(false)
// this.context.router.push('/upload');
// }else{
// console.log('No Dude')
// this.props.popErrorNotification(true,"#FF5D5D","Current Max Photo 5")
// }
}
loggedInMenu(){
return(
<div>
<li>Explore</li>
<li>My uploads</li>
{this.props.toggle.removeUploadMenu ?
<li>
<label htmlFor="upload-photo">Upload</label>
<input onChange={this.handleFileUpload.bind(this)} id="upload-photo" type="file" multiple/>
</li>:
""
}
<li>Profile</li>
<li>Logout</li>
</div>
)
}
loggedOutMenu(){
return(
<div>
<li onClick={()=>this.props.toogleSignInOut(true)}>SignUp/SignIn</li>
<li>Explore</li>
</div>
)
}
renderMenu(){
return(
<div onMouseLeave={this.UnHovered}>
<div className="dtcen">
<div className="dt">
</div>
</div>
<div className="dropdown">
{this.props.logInStatus.loginStatus ? this.loggedInMenu():this.loggedOutMenu()}
</div>
</div>
)
}
Hovered(){
this.props.toggleMenu(true);
}
render(){
// console.log('From uuis',this.uniqueNameAndId())
//console.log("Login Status",this.props.toggle.removeUploadMenu)
return(
<header>
<div className="logo">
<p>Masklor </p>
</div>
<div className="navtoggle">
<div onMouseEnter={this.Hovered} className="triangle">
<p>Menu</p>
</div>
{this.props.toggle.menuToggle ? this.renderMenu() : ""}
</div>
</header>
)
}
}
const mapStateToProps = (state) => {
return{
toggle:state.toggle,
logInStatus:state.logInStatus,
photos:state.photoUpload
}
};
const mapDispatchToProps = (dispatch) => {
return{
toggleMenu:bool => dispatch(headerAction.toggleStatus(bool)),
toogleSignInOut:bool => dispatch(headerAction.toggleSignPop(bool)),
pushtoReducer:object => dispatch(uploadActions.setPhotosState(object)),
popErrorNotification:(bool,color,message) => dispatch(notificationActions.popUpNotification(bool,color,message)),
removeUploadMenu:bool => dispatch(headerAction.removeUploadMenu(bool)),
setMainPostId:id =>dispatch(uploadActions.setIdforMainPost(id))
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Header)
I see your code might be generating javascript functions inside control flow blocks, in chorme ie will work fine but wont with mozilla, so you will have to put functions outside conditional blocks, see my sample:
In mozilla, this wont work:
function myDataCall(data) {
if(data) {
processData(data);
function processData(obj) {
console.log(obj);
}
}
}
This will work:
function myDataCall(data) {
//Work, cross browser compatible
if(data) {
processData(data);
}
function processData(obj) {
console.log(obj);
}
}
I hope this helps, regards!

how to properly iterate through array of post objects retrieved through Wp Rest Api in react js

hello :) i am working on wp rest api and react js and i successfully retrieved data from wp rest api and displayed it, but its not the proper way to display data in react. console is showing the error message of ' Each child in an array or iterator should have a unique "key" prop ' . I read the document in react regarding the issue but didn't understood . Here is what i have written so far. Any help would be great thank you
class Home extends React.Component{
componentDidMount(){
const API_URL = 'http://localhost/wordpress/wp-json/wp/v2/posts/';
this.serverRequest = $.get(API_URL, function (result) {
this.setState({
result:result,
loaded:true
});
}.bind(this));
}
constructor(props) {
super(props);
this.state ={result:null,loaded:false};
autoBind(this);
}
render(){
if (this.state.loaded) {
return(
<div>
{this.state.result && <Portfolio data = {this.state.result}/>}
</div>
)
}
return(
<div>loading...
</div>
)
}
}
export default Home;
and the Portfolio component to which prop data is passed renders the data like this which is not the proper way
class Portfolio extends React.Component{
constructor(props) {
super(props);
autoBind(this);
}
render(){
var contents=[];
for (var i = 0; i < this.props.data.length; i++) {
if (this.props.data[i].categories[0] == 5) {
var productImage ={
backgroundImage:'url('+ this.props.data[i].featured_image + ')',
backgroundSize: '100% 100%'
}
contents.push(
<div id="portfolio-product-item" style ={productImage} >
<div id ="portfolio-product-item-details" >
<h3>{this.props.data[i].slug}</h3>
<div dangerouslySetInnerHTML={{__html: this.props.data[i].content.rendered}} />
</div>
</div>
);
}
}
return(
<section className="portfolio">
{contents}
</section>
)
}
}
export default Portfolio;
I haven't went over all of your code, just relating to the "key" error you got.
The issue is here -
contents.push(
<div id="portfolio-product-item" style ={productImage} >
<div id ="portfolio-product-item-details" >
<h3>{this.props.data[i].slug}</h3>
<div dangerouslySetInnerHTML={{__html: this.props.data[i].content.rendered}} />
</div>
</div>
);
The father div with the id of portfolio-product-item should also have an attribute key so the proper way to write it is -
contents.push(
<div key={i} id="portfolio-product-item" style ={productImage} >
<div id ="portfolio-product-item-details" >
<h3>{this.props.data[i].slug}</h3>
<div dangerouslySetInnerHTML={{__html: this.props.data[i].content.rendered}} />
</div>
</div>
);
Have a look at - https://facebook.github.io/react/docs/multiple-components.html#dynamic-children for further info.
To make your Portfolio component cleaner.
I suggest, split the logic and create a separate method from the main render.
class Portfolio extends React.Component{
constructor(props) {
super(props);
autoBind(this);
}
renderPortfolioOption(index, option) {
const { data } = this.props;
if (option.categories[0] == 5) {
var productImage ={
backgroundImage:'url('+ option.featured_image + ')',
backgroundSize: '100% 100%'
}
return(
<div key={index} id="portfolio-product-item" style ={productImage} >
<div id ="portfolio-product-item-details" >
<h3>{option.slug}</h3>
<div dangerouslySetInnerHTML={{__html: option.content.rendered}} />
</div>
</div>
);
}
}
render() {
const { data } = this.props;
if (data.length) return null;
return(
<section className="portfolio">
{ data.map((index, option) => { return this.renderPortfolioOption(index, option); }) }
</section>
)
}
}
export default Portfolio;

Categories

Resources