Last active
November 21, 2018 19:13
-
-
Save crshmk/685933c91959e58bc30892af4ed64d63 to your computer and use it in GitHub Desktop.
redux async structures
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
function fetcher(url) { | |
return fetch(url).then(res => res.json()) | |
} | |
async function get(url) { | |
var result = await fetcher(url); | |
return result | |
} | |
get('https://jsonplaceholder.typicode.com/users') | |
.then(res => {console.log(res)}) | |
.catch(err => {console.log(err)}) |
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
async function get(url) { | |
try { | |
let response = await fetch(url).then(res => res.json()) | |
return {success: true, data: response } | |
} catch (e) { | |
return {success: false, data: e.message } | |
} | |
} | |
let url = 'https://jsonplaceholder.typicode.com/users' | |
let users = await get(url) | |
// {success: true, data: Array(10)} |
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
let API = { | |
get: (url) => | |
fetch(url) | |
.then(res => res.json()) | |
.catch(err => err) | |
} | |
let mapDispatchToProps = dispatch => ({ | |
getUsers: (url) => { | |
API.get(url) | |
.then(res => {dispatch(updateUsers(res))}) | |
.catch(err => {dispatch(getUserError(err))}) | |
} | |
}) | |
// simulate in console | |
var dispatch = x => null | |
var updateUsers = res => {console.log('update users with data', res)} | |
var getUserError = err => {console.log('error is ', err)} | |
var props = mapDispatchToProps(dispatch) | |
props.getUsers('https://jsonplaceholder.typicode.com/users') |
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
var get = (url) => | |
fetch(url) | |
.then(res => res.json()) | |
.catch(err => err) | |
var url = 'https://jsonplaceholder.typicode.com/users' | |
get(url).then(res => {console.log(res)}).catch(err => console.log(err)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fetch and return a promise
redux async flow without middleware / related