Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  123] [ 7]  / answers: 1 / hits: 21330  / 6 Years ago, mon, march 26, 2018, 12:00:00

Just wanted to know how to group all of my API calls altogether in an api.js file, in my React App (just some pseudocode would work). I have read an interesting article that introduces that idea, and I feel curious because that file structure really fits my needs. How would it be?
Moreover, the author states in a comment:




I usually just put all of my API calls into that file - they're
usually small one-or-two-line functions that call out to axios, and I
just export them.



export function login(username, password) { ... } export function
getFolders() { ... } etc.




But I feel it lacks some details to reproduce it. I am new to Javascript and React. Thanks.


More From » reactjs

 Answers
6

Say you are using axios for http calls, I guess it would be smth like this:


api.js:


import axios from 'axios';
import { resolve } from './resolve.js';

export async function login(user, pass) {
return await resolve(axios.post('http://some-api.com/auth', { user, pass }).then(res => res.data));
}

export async function getUser(id) {
return await resolve(axios.get(`http://some-api.com/users/${id}`).then(res => res.data));
}

// and so on....

And as he said on the post, If your files starts to get too big, you can create a src/api/ and create separate files like src/api/auth.js, src/api/users.js, etc..


To resolve the promises I like to use the new async/await syntax and wrap it in a little module resolver.js:


export function async resolve(promise) {
const resolved = {
data: null,
error: null
};

try {
resolved.data = await promise;
} catch(e) {
resolved.error = e;
}

return resolved;
}

And your component smth like:


// ...
componentDidMount() {
this.getUser();
}

async getUser() {
const user = await api.getUser(this.props.id);
if(user.error)
this.setState({ error: user.error });
else
this.setState({ user: user.data });
}

Again, this is something I like to do, I think the code looks clearer, keeping a synchronous structure. But I guess it's perfectly fine to resolve your promises with .then() and .catch() also.


I hope that helped!


[#54847] Thursday, March 22, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;