r/reactjs • • Jul 01 '18

Help Beginner's Thread / Easy Question (July 2018)

Hello! just helping out /u/acemarke to post a beginner's thread for July! we had almost 550 Q's and A's in last month's thread! That's 100% month on month growth! we should raise venture capital! /s

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch. No question is too simple. You are guaranteed a response here!

New to React? Free, quality resources here

Want Help on Code?

  • Improve your chances of getting helped by putting a minimal example on to either JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new). Describe what you want it to do, and things you've tried. Don't just post big blocks of code.
  • If you got helped, pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.
51 Upvotes

454 comments sorted by

View all comments

Show parent comment

2

u/molszanski Jul 27 '18
// api.js file
import axios from 'axios';
import React from 'react';

let prefix = 'pizza';
if (Math.random() > 0.5) {
  prefix = 'burger';
}
export const API = axios.create({
  baseURL: `https://${prefix}.com/api`,
});

// SomeComponent.js
import { API } from './api';
export default class Person extends React.Component {
  load() {
    API.get(`/user`).then(res => {
      console.log(res);
      console.log(res.data);
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.load.bind(this)} />
      </div>
    );
  }
}

2

u/[deleted] Jul 27 '18

Cheers. Yeah that's almost identical to what my team member wrote. Having just come from the Angular world it's a bit of an adjustment for me THB.