Whether you’re a Bootcamp grad, a recent CS grad, or a professional web developer, you’ll likely encounter this problem at some point in your career. It can be a question asked during a frontend coding interview or a ticket on your scrum board that your tech lead wants you to take on.
I’ve had at least five different interviews (frontend and full-stack) that have asked me to do this: “Make a GET request from an API endpoint and populate the data on the screen in a React component”. Make sure you know how to do so for both class and functional components with or without hooks. What did the companies ask me to do? I’ve anonymized the coding questions and changed the variable names, but the concept is there.
- Company A: Use fetch() API in a class component and save the response in
this.state.weeklyData. When different buttons are clicked, render the corresponding data onto the screen depending on which day was clicked.
- Company B: Use React hooks to save a fetched JSON data in a state variable called
recipe. Render all the
recipe.ingredientson to the screen as child nodes of
<ul id='list-container' data-testid='grocery-list'>.
- Company C: In
async/awaitwith fetch or axios to GET from an API the user data. Render the
<BadgeOfRecognition />component under the user’s name shown on the screen only if the user satisfies 3 conditions: (1) If
user.lastActiveshows that the user account has been active in the last three days, (2)
user.numOfFollowersis more than 500, and (3)
- Company D: Fetch from an API endpoint a JSON object where each key is the product category and the value array contains the corresponding products. Given a string
productNamepassed into the React functional component, check to see if it is under any of the product categories. If so, render the product category on the screen with a
<h2>tag, current product in an
<h3>tag, and all the other products under that same product category in an unordered list under the text “buyers who bought this item also bought”.
- Company E: In the
userScrolledToBottom()helper method, fetch from an API an array of 20 news articles. For each article, dynamically populate onto the screen
article.numOfLikesto replace our placeholder texts for each of these in the returned JSX in our functional component. The snippet should contain the first 150 characters from
Let’s dive right in!
First of all, let’s create a boilerplate React component. A great place to start is to use React’s create-react-app to start creating a single page application. Type these in your command-line tool.
$ cd desktop
$ npx create-react-app my-app
$ cd my-app
$ yarn start
Then open your browser to go to http://localhost:3000. Open the folder
my-app in your favorite coding editor, be it VS Code, Atom, Sublime, or VIM if you’re hardcore. Create-react-app uses
webpack under the hood. Hot-reload is enabled, so every time you modify any React.js file, you can just save the file and the browser automatically loads the new content without the need to recompile the code in the terminal.
fetch()from an astronaut API made by the Postman team with JSON data shown below. To format data in the Google Chrome browser, you can use the JSON Formatter Chrome extension.
We want to achieve a few goals:
- Fetch from an API endpoint using HTTP GET request.
- Save the fetched data in a state variable.
- Render the data onto the webpage.
Fetch from React class component:
After the initial render, the React lifecycle method
componentDidMount() is called. Even though
componentWillMount() happens before the first render, it’s not recommended for newer versions of React. Therefore, we have to initialize our
Array.map() method to create a list of DOM nodes to attach to the DOM tree. For this, React uses a diffing algorithm.
src/App.js and modify the file as below:
Fetch from React functional component:
We can use React hooks
useEffect() to our advantage.
Tip: The second argument of the
useEffect() method is called a “dependencies array”. If we want to run the effect only once and clean it up, we can pass an empty array
 . This way, React knows that our effect doesn’t depend on any values from state or props and never reruns. If you’d like to visualize the optimization difference,
console.log('running useEffect') between lines 11 and 12. Check your browser’s console. It should only print once. Now, delete the empty array on line 16 and check your browser's console again.