Loading images from Firebase Realtime Database + Storage

我与影子孤独终老i 提交于 2019-12-24 05:57:52

问题


I'm creating something like an image gallery of cars using create-react-app in Firebase documentation (react+redux+firebase). Images information are stored in Firebase Realtime Database, but the actual image files are stored in Firebase Storage. In componentWillMount, I called an action creator to fetch those images:

this.props.fetchCars();

In the action creator, this function executes:

export function fetchCars() {
  return (dispatch, getState) => {
         carsRef.on('value', snapshot => {
          dispatch({
              type: FETCH_CARS,
              payload: snapshot.val()
          });
      });
  };
}

That dispatch goes to my reducer and update the state accordingly. My state looks like this:

{
cars: {
  make: "Toyota",
  model: "Vios",
  year: 2015,
  fileName: "cars1.jpg",
  fileFullPath: ""
  }
}

After fetching, the full URL of the image is not yet known (fileFullPath), as fileName is just a file name uploaded by the user. So I have to use Firebase Storage to get the downloadable Url so I can put it in an <img /> tag:

export function getFileFullPath(){
    return (dispatch, getState) => {
     var newState = Object.assign({}, getState());
     var imgRef, carUrl;
     _.map(newState.cars, (car, index) => {
       imgRef = storageRef.child('images/'+car.img);
       carUrl = imgRef.getDownloadURL().then( url => {
            car.fileFullPath=url;
       });
     });

     dispatch({
         type: FILL_UP_URL,
         payload: newState.cars
     });
    };
}

However, when I run this, it doesn't work. After 1st dispatch, the images list were retrieved correctly from Realtime Database with empty fileFullPath. After 2nd dispatch it is still empty. I guess there's something wrong with the way I do this, but I don't know how to do it.

来源:https://stackoverflow.com/questions/39929187/loading-images-from-firebase-realtime-database-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!