UNPKG

storry

Version:

State Management made simple

68 lines (61 loc) 2 kB
<html> <head> <title>Storry Example</title> <meta charset="utf-8" /> </head> <body> <div id="root"></div> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react-dom.js"></script> <script src="../browser/storry.js"></script> <script src="../browser/storry-react.js"></script> <script type="text/babel"> const giphyAPI = 'https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=' //Create your store const store = storry({ counter: 42, topic: 'cat' }) //Define your actions const increaseCounter = store.action((state) => Object.assign({}, state, { counter: state.counter+1 })) const resetCounter = store.action((state) => Object.assign({}, state, { counter: 0 })) const updateTopicField = store.action((state, event) => Object.assign({}, state, { topic: event.target.value })) const updateImage = (state, image) => Object.assign({}, state, { image }) const loadRandomPic = () => fetch(giphyAPI + store.state().topic) .then(res => res.json()) .then(res => res.data.image_original_url) .then(store.action(updateImage)) //Define your App, receiving the state as props const App = (state) => <div> Counter: {state.counter} <br /> <button onClick={increaseCounter}>+</button> <br /><br /> <input type="text" onChange={updateTopicField} value={state.topic} /> <button onClick={loadRandomPic}>load random picture</button> <br /> <img src={state.image} /> </div> //Render your application wrapped ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ) //Have fun! //Set counter to 0 every 30 seconds setInterval(resetCounter, 30000) //Get a picture loadRandomPic() //Listen to state changes store.listen((state) => console.log('NEW STATE', state)) </script> </body> </html>