Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Last active January 3, 2019 15:29
Show Gist options
  • Save treyhuffine/a355b7babda25eefc1e86122e3bdc1bf to your computer and use it in GitHub Desktop.
Save treyhuffine/a355b7babda25eefc1e86122e3bdc1bf to your computer and use it in GitHub Desktop.
import React from 'react';
import Storage from 'components/Storage';
class ComponentNeedingStorage extends React.Component {
state = {
username: '',
favoriteMovie: '',
isFetching: false,
}
componentDidMount() {
const username = this.props.load('username') || this.state.username;
const favoriteMovie = this.props.load('favoriteMovie') || this.state.username;
if (!username || !favoriteMovie && !this.state.isFetching) {
this.fetchData();
}
}
fetchData() {
this.setState({ isFetching: true });
this.props.reallyLongApiCall()
.then((user) => {
this.props.save('username', user.username);
this.props.save('favoriteMovie', user.favoriteMovie);
this.setState({
username: user.username,
favoriteMovie: user.favoriteMovie,
isFetching: false,
});
});
}
render() {
if (this.state.isFetching) {
return (
<div>Loading...</div>;
);
} else {
<div>
My username is {username}, and I love to watch {favoriteMovie}.
</div>
}
}
}
class WrapperComponent extends React.Component {
render() {
return (
<Storage
render={({ load, save, remove }) => {
return (
<ComponentNeedingStorage
load={load}
save={save}
remove={remove}
/>
)
}}
/>
);
}
}
@treyhuffine
Copy link
Author

@treyhuffine so in the "really long api call" where is "user" coming from?

This would be the response from a server API call. For examples /api/users/1 would response with a JSON object of a user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment