Skip to content

Commit

Permalink
Implement the file upload to the server store hook
Browse files Browse the repository at this point in the history
  • Loading branch information
christianbiring1 committed Jan 22, 2023
1 parent e443b89 commit 86c80c8
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/components/createItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,14 @@ class CreatePost extends Form {
id: auth.currentUser.uid,
};
const posts = collection(db, "posts");
console.log(file);

const types = ['image/png', 'image/jpeg', 'image/jpg', '.gif'];
if (types.includes(!file.type)) {
console.log('Wrong file');
return
};


try {
await addDoc(posts, {
title,
Expand All @@ -44,7 +51,7 @@ class CreatePost extends Form {
const errorCode = error.code;
console.log(error);
const errors = { ...this.state.errors };
errors.title = errorCode;
errors.file = errorCode;
this.setState({ errors });
}
};
Expand Down
9 changes: 9 additions & 0 deletions src/components/progress.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/* eslint-disable */
import React from 'react';
import FileUpload from '../hooks/Hookstorage';

const ProgressBar = () => (
<div className="progress" />
);

export default ProgressBar;
33 changes: 33 additions & 0 deletions src/hooks/Hookstorage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* eslint-disable */
import { useState, useEffect } from 'react';
import * as firebase from 'firebase/app';
import 'firebase/storage';
import 'firebase/firestore';

const projectStore = firebase.storage();

const FileUpload = (file) => {
const [progress, setProgress] = useState(null);
const [error, setError] = useState(null);
const [url, setUrl] = useState(null);

useEffect(() => {
// References
const storageRef = projectStore.ref(file.name);

storageRef.put(file).on('state_changed', (snap) => {
let percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
setProgress(percentage);
}, (error) => {
setError(error);
}, async () => {
const url = await storageRef.getDownloadURL();
setUrl(url);
})
}, [file])

return { progress, url, error }

}

export default FileUpload;

0 comments on commit 86c80c8

Please sign in to comment.