In chapter 4. Write Klaystagram Smart Contract, we wrote PhotoData struct, and located it inside _photoList mapping. Feed component's role is as follows: 1. Read PhotoData via calling Klaystagram contract method (redux/actions/photos.js) 2. Show PhotoData(feed) with its owner information (components/Feed.js)
2) Read data from contract: getPhoto method
Call contract method: getTotalPhotoCount()
If there are zero photos, call setFeed action with an empty array.
Call contract method:getPhoto(id)
If there are photos, get each photo data as a promise and push it in the feed array. When all promises have resolved, return the feed array.
Call redux action: setFeed(feed)
Get resolved feed array and save it to redux store.
// src/redux/actions/photos.jsconstsetFeed= (feed) => ({ type:SET_FEED, payload: { feed },})exportconstgetFeed= () => (dispatch) => {// 1. Call contract method(READ): `getTotalPhotoCount()`// If there is no photo data, call `setFeed` action with empty arrayKlaystagramContract.methods.getTotalPhotoCount().call().then((totalPhotoCount) => {if (!totalPhotoCount) return []constfeed= []for (let i = totalPhotoCount; i >0; i--) {// 2. Call contract method(READ):`getPhoto(id)`// If there is photo data, call all of themconstphoto=KlaystagramContract.methods.getPhoto(i).call()feed.push(photo) }returnPromise.all(feed) }).then((feed) => {// 3. Call actions: `setFeed(feed)`// Save photo data(feed) to storedispatch(setFeed(feedParser(feed)) })}
3) Save data to store: setFeed action
After we successfully fetch photo data (feed) from the Klaystagram contract, we call setFeed(feed) action. This action takes the photo data as a payload and saves it in a redux store.
At the first time, you can only see the text "No photo :D" because there is no photo data in contract yet.
Let's make a UploadPhoto component to send photo data to contract!