Skip to content

Instantly share code, notes, and snippets.

@ac205
Created January 13, 2020 00:45
Show Gist options
  • Save ac205/4f931f83018b6bcc2bcb9fb7bcccb7d1 to your computer and use it in GitHub Desktop.
Save ac205/4f931f83018b6bcc2bcb9fb7bcccb7d1 to your computer and use it in GitHub Desktop.
FB/Redux Help
import React from "react";
import { connect } from "react-redux";
const ImageUpload = ({ url, progress, handleImgUpload }) => {
const handleChange = e => {
if (e.target.files[0]) {
const image = e.target.files[0];
handleImgUpload(image);
}
};
const style = {
height: "100vh",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center"
};
return (
<div style={style} key={url}>
<progress value={progress} max="100" />
<br />
<input type="file" onChange={handleChange} />
<br />
<img
src={url}
alt="Uploaded images"
height="300"
width="400"
object-fit="contain"
/>
{"this is the url" + url}
</div>
);
};
const mapStateToProps = state => {
return {
products: state.shopReducer.products,
progress: state.adminReducer.progress,
url: state.adminReducer.url
};
};
const mapDispatchToProps = dispatch => {
return {
handleImgUpload: image => {
dispatch({ type: "UPLOAD_IMAGE", payload: image });
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageUpload);
const adminReducer = (
state = {
progress: 0,
url: "hi",
},
action
) => {
switch (action.type) {
case "UPLOAD_IMAGE":
const image = action.payload;
let imgURL = "";
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on(
"state_changed",
snapshot => {
// progress function ....
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
state = {
...state,
progress
};
},
error => {
// error function ....
console.log(error);
},
() => {
// complete function ....
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
console.log(url);
imgURL = url;
});
}
);
state = {
...state,
img: imgURL
};
break;
default:
}
return state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment