Last active
August 26, 2018 13:00
-
-
Save taktran/d25baf714a8ef078289a019dd97dffa1 to your computer and use it in GitHub Desktop.
Unstated Api example
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 React from "react"; | |
import { Provider, Subscribe, Container } from "unstated"; | |
import ApiService from './utils/api-service'; | |
const DEFAULT_STATE = { | |
loggedIn: false, | |
user: {}, | |
errors: [] | |
}; | |
const HTTP_OK = 200; | |
export class ApiContainer extends Container { | |
constructor() { | |
super(); | |
this.state = DEFAULT_STATE; | |
} | |
async login({ username, password }) { | |
return ApiService.login({ username, password }) | |
.then(this.handleServerError) | |
.then(user => | |
this.setState({ | |
loggedIn: true, | |
user | |
}) | |
) | |
.catch(this.setErrorStateAndThrow); | |
} | |
async logout() { | |
this.setState(DEFAULT_STATE); | |
return ApiService.logout(this.state.user); | |
} | |
resetErrors() { | |
this.setState({ | |
errors: [] | |
}); | |
} | |
handleServerError(res) { | |
const { statusCode = HTTP_OK } = res; | |
if (statusCode !== HTTP_OK) { throw res; } | |
return res; | |
} | |
setErrorStateAndThrow = e => { | |
this.setState({ | |
errors: [ e ] | |
}); | |
throw(e); | |
}; | |
} | |
const Api = new ApiContainer(); | |
export const ApiProvider = props => { | |
return <Provider inject={props.inject || [ Api ]}>{props.children}</Provider>; | |
}; | |
export const ApiSubscribe = props => { | |
return <Subscribe to={props.to || [ Api ]}>{props.children}</Subscribe>; | |
}; | |
// Export an instance singleton | |
export default Api; |
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 React, { Component } from 'react'; | |
import { ApiProvider } from './Api'; | |
// Some root component | |
class App extends Component { | |
render() { | |
return ( | |
<ApiProvider> | |
// Some children | |
</ApiProvider> | |
) | |
} | |
} | |
export default App; |
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 React, { Component } from 'react'; | |
import Api, { ApiSubscribe } from './Api'; | |
// Example of using state | |
const Component = (props) => { | |
return <ApiSubscribe> | |
{({ state }) => { | |
return <div>state.loggedIn</div> | |
}} | |
</ApiSubscribe>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment