Last active
December 30, 2018 11:35
-
-
Save shalvah/2d0d048f87b9664e2a86adcbdbb53119 to your computer and use it in GitHub Desktop.
Basic example of how Redux could be used to manage state in a frontend app like Twitter Lite (mobile.twitter.com)
This file contains 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
import { createStore } from 'redux'; | |
// our reducer | |
const tweets = (state = {tweets: []}, action) => { | |
switch (action.type) { | |
// we'll handle only one action: when new tweets arrive | |
case 'SHOW_NEW_TWEETS': | |
state.numberOfNewTweets = action.count; | |
return state.tweets.concat([action.tweets]); | |
default: | |
return state; | |
} | |
}; | |
// a helper function to create the SHOW_NEW_TWEETS action | |
const newTweetsAction = (tweets) => { | |
return { | |
type: 'SHOW_NEW_TWEETS', | |
tweets: tweets, | |
count: tweets.length | |
}; | |
}; | |
const store = createStore(tweets); | |
twitterApi.fetchTweets() | |
.then(response => { | |
// instead of manually adding the new tweets to the view, | |
// we dispatch the Redux action | |
store.dispatch(newTweetsAction(response.data)); | |
}); | |
// we also use the SHOW_NEW_TWEETS action when the user tweets | |
// so the user's tweet is added to the state too | |
const postTweet = (text) => { | |
twitterApi.postTweet(text) | |
.then(response => { | |
store.dispatch(newTweetsAction([response.data])); | |
}); | |
}; | |
// supposing we have new tweets being pushed to the frontend via WebSockets, | |
// we can also dispatch the SHOW_NEW_TWEETS action | |
socket.on('newTweets', (tweets) => { | |
store.dispatch(newTweetsAction(tweets)); | |
}; | |
// If we're using a framework like React, our components should be connected to our store, | |
// and should auto-update to show the tweets | |
// otherwise we can manually listen for state changes | |
store.subscribe(() => { | |
const { tweets } = store.getSTate(); | |
render(tweets); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment