DEV Community

Marcin Oleksiak
Marcin Oleksiak

Posted on • Updated on

Fetching Yelp API via Netlify Function with React.js [pt. 3]

Previous part covering steps 6-9 is right here.

In this part I will:

  • register to Yelp Fusion API and get API Key
  • using API Key will fetch data with Postman.app
  • install react-router-dom package and scaffold some navigation
  • make use of useHistory hook, add query string to URL
  • apply conditional rendering for Fetched component
  • install react-router-dom package and use it with useLocation hook to parse query string from URL
  • utilize useEffect hook to make an attempt to fetch data from Yelp API

10. Yelp API

In order to sign up for Yelp Developers I need to visit https://www.yelp.com/developers website, click the Sign Up button and follow the procedure.

When I'am successfully logged in and still at https://www.yelp.com/developers, I can click on Yelp Fusion link which will take me to https://www.yelp.com/fusion. Then, at the top of the page, I click on Fusion API link and I am at https://www.yelp.com/developers/documentation/v3. Now I can create my app. To do it, I click on Create App link (under General category).

I need to give my app some name, choose industry, enter my email address and write some short app description. Finally, I need to check all three options and only then I can click Create New App button.

When my app is created, I'm transferred to https://www.yelp.com/developers/v3/manage_app, where I can see confirmation message, my ID and my API Key:

Alt Text

I need to keep my API Key in save, secret place, never deploy it to web server, never push to GitHub. I can start using Postman app now.

11. Postman

Postman is free and can be downloaded from this place: https://www.postman.com/downloads/

The most active Postman expert I found on the web is Valentin Despa. I discovered his 6 videos course on Postman YouTube channel titled Intro to Postman (started on 2019-10-03, duration 54:10 in total). Recently (2021-03-01) Valentin published a massive (2:09:37) course on freeCodeCamp.org YouTube channel titled Postman Beginner's Course - API Testing.

For this particular project, the shortest and quickest way to start using Postman is go to Yelp API documentation and click on Run in Postman button:

Alt Text

I choose to work in desktop app, so I click this link:

Alt Text

A collection of six endpoints called Yelp V3 was uploaded into my Postman app:

Alt Text

I'm interested in the third one, called /businnesses/search. Full documentation for this endpoint is available here.

11.1 Query Params

I will use two first Parameters from documentation: term and location, and I will assign to them pizza and Berlin values respectively.

Alt Text

Postman will pass those Parameters to the end of a URL in the form of key=value pairs.

Alt Text

11.2 Authorization

To authorize, I need to open Authorization tab and choose Bearer Token as my authorization type. All of them are described in Postman's documentation. In the Token text area I paste my API Key:

Alt Text

11.3 Sending GET request

I'm ready to fetch data from Yelp API. I click the Send button:

Alt Text

Yelp API returns businesses array of 20 objects (that's the limit in Yelp API). Each object contains full info about particular restaurant:

Alt Text

In this step I fetched Yelp API data with Postman app. In the next steps I will try to fetch again, this time with my React app.

12. React Router

There is an excellent and complete course about React Router on YouTube: React Router Crash Course (published 2020-06-09, recording duration 1:51:10), created by Sanjeev Thiyagarajan.

Official documentation with plenty of code examples is provided by React Training, company that stands behind React Router library.

So in order to install and use it in my project, I need to install react-router-dom package by running this command:

yarn add react-router-dom

12.1 BrowserRouter component

According to official docs, it keeps entire UI in sync with the URL.

~/src/index.js

Alt Text

12.2 Switch and Route components, exact property

Switch component renders UI exclusively (first child component that matches current URL).
Route component renders UI inclusively (every child component that matches current URL).
exact property renders UI only if full path is matched

~/src/App.jsx

Alt Text

12.3 NavLink component

NavLink component allows to navigate around UI.

~/src/comps/Nav.jsx

Alt Text

Additionally NavLink component adds styling attributes to the rendered element:

DevTools > Inspector

Alt Text

12.4 useHistory hook and history object

Basic purpose of using the history object is well explained in React Router DOM tutorial (published 2020-05-11, recording duration 17:57, starting at 1:48) by Mauricio Leal. I used it to programmatically change the route by pushing in it a query string which is based on the Yelp API guidelines.

~/src/comps/Inputs.jsx

Alt Text

In order to check this code, I type pizza in food input field, Berlin in town input field and I click Search button. My recent URL looks like this:

http://localhost:3000/search?term=pizza&location=Berlin

When I click homepage link, my app is back at http://localhost:3000/

13. Preparing Fetched component

Eventually I wanna render Fetched component ONLY if Search button is clicked. If homepage link is clicked, I want Fetched component to disappear. My idea will work like this:

  1. When app is launched, Fetched component will NOT be rendered:

Alt Text

  1. Only after entering some search criteria, e.g. pizza/Berlin and submitting them, GET request will be sent. Only then, regardless of successful or failed Yelp API response will be, Fetched component WILL be rendered.
  • if GET request will be successful, fetched data will be rendered too:

Alt Text

  • if GET request will fail (e.g. due some misspell: Berlim instead of Berlin), the appropriate message will show up:

Alt Text

  1. After clicking on homepage link, Fetched component's state will be cleared and Fetched component itself will disappear:

Alt Text

13.1 Emptying state

To give myself ability to clear Fetched component's state when clicking on homepage link, I need to do the following:

  • bring setSubmitting function from App component as a prop to Nav component

~/src/App.jsx

Alt Text

~/src/comps/Nav.jsx

Alt Text

  • initialize event handler (I will called it cleanInputsFx) and utilize setSubmitting function in it

~/src/comps/Nav.jsx

Alt Text

  • invoke onClick event in homepage link

~/src/comps/Nav.jsx

Alt Text

Now I can check how it works:

  • first things first, yarn start command, browser is running at http://localhost:3000/

  • I enter some search criteria, e.g. pizza/Berlin and submit them. Of course nothing is fetched yet, but I can see entered data in submitting prop of Fetched component:

DevTools > Components > App > Fetched

Alt Text

  • I click homepage link and submitting prop is cleared:

DevTools > Components > App > Fetched

Alt Text

13.2 Clearing input fields when homepage link in clicked

Let's say I entered some search criteria, e.g. pizza/Berlin but instead of submit them, I click homepage link. In this scenario I need to clear both input fields. In other words, I need to clear entering state. I will do it in the following steps:

  • bring setEntering function from App component as a prop to Nav component

~/src/App.jsx

Alt Text

~/src/comps/Nav.jsx

Alt Text

  • make use of setEntering function in cleanInputsFx event handler:

~/src/comps/Nav.jsx

Alt Text

  • Now I will check my code. I enter some search criteria, e.g. pizza/Berlin but NOT submit them:

Alt Text

  • I click homepage link

Alt Text

13.3 Conditional rendering

In order to conditionally show/hide Fetched component, I must undertake the following steps:

  • in App component initialize new state with boolean value false assigned

~/src/App.jsx

Alt Text

  • pass setFetchedVisible function as prop to Nav component

~/src/App.jsx

Alt Text

  • pass setFetchedVisible function as prop to Input component

~/src/App.jsx

Alt Text

  • add inline if contition (fetchedVisible variable's boolean value is equal to true) with logical AND operator to Fetched component

~/src/App.jsx

Alt Text

  • import setFetchedVisible prop to Nav component and use it inside of cleanInputsFx event handler.

~/src/comps/Nav.jsx

Alt Text

  • import setFetchedVisible prop to Inputs component and use it inside of submittingFx event handler.

~/src/comps/Inputs.jsx

Alt Text

  • one last minor fix: to make homepage link well visible, I will change browser's default link color to this:

~/src/App.scss

Alt Text

Now I can check how it works:

Alt Text

  • I enter some search criteria, e.g. pizza/Berlin and submit them. Of course nothing is fetched yet, but Fetched component is rendered.

Alt Text

  • I click homepage link, Fetched component disappears:

Alt Text

14. Fetching Yelp API (first attempt)

In this section I will initialize ENDPOINT variable dynamically, meaning its value will be based on search criteria entered into input fields and submitted with Search button.

Also, I will initialize API_KEY variable with Yelp API Key value copied from my Yelp account (available here: ) and pasted into my code. I will NOT commit or push to GitHub code with Yelp API Key value in it, I will blur it in screenshots. This is sensitive and confidential data, eventually I will keep it as environment variable on Netlify cloud.

14.1 useLocation hook and query-string package

In step 12.4 I dynamically generated URL with query string: http://localhost:3000/search?term=pizza&location=Berlin. “dynamically” means that if I will search for fish in Sydney, my URL will change: http://localhost:3000/search?term=fish&location=Sydney.

In this step I will

  • parse this URL
  • pull both searching criteria out of it
  • inject them into ENDPOINT variable
  1. useLocation hook is explained in tutorial I mentioned already in step 12.4, React Router DOM (starting at 5:44). I will use it to parse entire URL, identify query string in it and assign it to new variable.

~/src/comps/Fetched.jsx

Alt Text

DevTools > Console

Alt Text

useLocation hook returned a Object and I am interested in two particular values: pathname and search. I will use them to build my ENDPOINT.

  1. To continue, I need to install query-string package. I figured out how to use it from How to store data in the URL query string using React Router tutorial (published 2020-05-12, recording duration 8:01) by Frederik Diekmann. Official docs are also helpful.

yarn add query-string

With query-string package I will pull out searching criteria from search value:

~/src/comps/Fetched.jsx

Alt Text

DevTools > Console

Alt Text

  1. Okay, I have all I need to initialize my ENDPOINT:

~/src/comps/Fetched.jsx

Alt Text

DevTools > Console

Alt Text

My ENDPOINT is exactly the same as GET request from step 11.1. I'm almost ready to fetch some data!

14.2 useEffect hook

The most comprehensive useEffect hook tutorial I found on YouTube is useEffect React Hook the complete guide (published 2021-04-20, recording duration 48:27) by Sanjeev Thiyagarajan. ToC is impressive: what is a useEffect hook, dependency array, local storage, rendering order, data fetching, and there is more!

So, finally in this step, I will try to fetch Yelp API and return fetched data to the browser's console. I will initialize fetchingYelpFx async function, utilize try...catch statement, use fetch method to authorize with my API_KEY variable placed temporarily in my code and invoke fetchingYelpFx on the end of useEffect hook. This is my code:

~/src/comps/Fetched.jsx

Alt Text

If my app is running at http://localhost:3000/, I can check my code by entering pizza in food input field, Berlin in town input field and I click Search button to see what will happen.

14.3 PROBLEM : CORS header 'Access-Control-Allow-Origin' missing

DevTools > Console

Alt Text

So this is the first problem I've got. Cross-Origin Resource Sharing (CORS) mechanism is well explained here. CORS error messages in general are described here, the error I'm struggling with, CORS header 'Access-Control-Allow-Origin' missing, is clarified here. I will resolve this problem in the next part.

14.4 PROBLEM : API_KEY is visible

DevTools > Network > GET > Headers

Alt Text

At this stage of my project I keep my Yelp API Key in my frontend code. This is provisional, but as a result I can see the API_KEY variable's value in my browser's DevTools, more precisely in Network tab. I will fix that in the next part.

14.5 Code on GitHub, what's next?

Complete repo from this blog entry is uploaded on my GitHub.

Next part covering steps 15-18 is right here.

Thanks for reading and stay tuned!

Discussion (0)