I’m working a side project using react, redux and firebase as backend.
Right now I was looking a way to store the URL of the image I was uploading into my firestore database along side other data.
This is what is working at the moment:
Action addProduct.js
export const addProduct = (product) => {
return (dispatch, getState, { getFireStore }) => {
const db = firestore;
const uploadTask = storage.ref(`images/${product.image.name}`).put(product.image);
uploadTask.on(
"state_changed",
snapshot => {},
error => {
console.log(error);
},
() => {
storage
.ref("images")
.child(product.image.name)
.getDownloadURL()
.then(url => {
let updatedProduct = {
...product,
image: url
}
db.collection('products').add({
...updatedProduct,
}).then(() => {
dispatch({
type: ADD_PRODUCT,
updatedProduct
})
}).catch((err) => {
dispatch({ type: ADD_PRODUCT_ERR, err })
})
})
}
)
}
Couple of things bugging me here:
- While it successfully uploads the image and stores its url in the database, this code looks really messy from my perspective. Can an action file be this complex? Is there a more cleaner way to do this?
- My reducer is returning an undefined payload for some reason I can’t find.
Reducer productReducer.js
import { ADD_PRODUCT, ADD_PRODUCT_ERR } from "../actions/types"
const initialState = {
product: null
}
export default (state = initialState, action) => {
switch(action.type) {
case ADD_PRODUCT:
console.log('Product Added', action.product)
return state
case ADD_PRODUCT_ERR:
console.log('Product Failed', action.err)
return state
default:
return state
}
}