Created
July 26, 2015 02:40
-
-
Save brysgo/f9613e71386b00aa4d03 to your computer and use it in GitHub Desktop.
Example of using Relay inspired framework `react-transmit` with temporary client side state.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/views/Advert.js | |
import __fetch from "isomorphic-fetch"; | |
import React from "react"; | |
import Transmit from "react-transmit"; | |
import AdvertStore from "stores/AdvertStore"; | |
import _ from "utils/Utils"; | |
class Advert extends React.Component { | |
render () { | |
return ( | |
<img alt="advertisement" style= className="ad" src={this.props.adImage}/> | |
); | |
} | |
} | |
export default Transmit.createContainer(Advert, { | |
queryParams: { | |
adId: undefined, | |
index: undefined, | |
}, | |
queries: { | |
adImage (queryParams) { | |
const adId = queryParams.adId || AdvertStore.randomUniqueIdFromIndex(queryParams.index); | |
const adApi = `http://${_.host()}/ad`; | |
const imageUrl = adApi + '?' + _.param({r: adId}); | |
// use fetch to get the image since the browser will use cache once it has been fetched | |
return fetch(imageUrl).then(() => imageUrl); | |
} | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/stores/AdvertStore.js | |
export default class AdvertStore { | |
static randomUniqueIdFromIndex (index) { | |
let result = AdvertStore._indexIdMap[index]; | |
if (result) return result; | |
if (Object.entries(AdvertStore._usedIds).length > 100) AdvertStore._usedIds = {}; | |
while (AdvertStore._usedIds[result]) { | |
result = Math.floor(Math.random()*1000); | |
} | |
AdvertStore._usedIds[result] = true; | |
AdvertStore._indexIdMap[index] = result; | |
return result | |
} | |
} | |
AdvertStore._usedIds = { undefined: true }; | |
AdvertStore._indexIdMap = { }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment