The Most Common React Interview Coding Question — Fetch and Display
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 therecipe.ingredients
on to the screen as child nodes of<ul id='list-container' data-testid='grocery-list'>
. - Company C: In
App.js
useasync/await
with 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) Ifuser.lastActive
shows that the user account has been active in the last three days, (2)user.numOfFollowers
is more than 500, and (3)user.isPremiumMember
is true. - 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
productName
passed 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 screenarticle.title
,article.snippet
, andarticle.numOfLikes
to replace our placeholder texts for each of these in the returned JSX in our functional component. The snippet should contain the first 150 characters fromarticle.content
.
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 babel
and 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.
Let’s 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 thoughcomponentWillMount()
happens before the first render, it’s not recommended for newer versions of React. Therefore, we have to initialize our astronauts
state variable to an empty array, so the compiler doesn’t complain during the first render. We can use JavaScript’s Array.map()
method to create a list of DOM nodes to attach to the DOM tree. For this, React uses a diffing algorithm.
Open src/App.js
and modify the file as below:
What if you want to use a React functional component instead? No problem. After all, functional components are the way to go! They prevent hidden states, side effects, and a bloated application.
Fetch from React functional component:
We can use React hooks useState()
and useEffect()
to our advantage.
Tip: The second argument of theuseEffect()
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.
Want to keep a copy of the code for the class or functional component? Feel free to fork it to your own GitHub or star it to come back later. Trust me, you’ll encounter this question A LOT.