Ravenous Part 3: Setting the Search Bar's State

Congratulations on completing your project!

Compare your project to our solution code and share your project below! Your solution might not look exactly like ours, and that’s okay! The most important thing right now is to get your code working as it should (you can always refactor more later). There are multiple ways to complete these projects and you should exercise your creative abilities in doing so.

This is a safe space for you to ask questions about any sample solution code and share your work with others! Simply reply to this thread to get the conversation started. Feedback is a vital component in getting better with coding and all ability levels are welcome here, so don’t be shy!

About community guidelines: This is a supportive and kind community of people learning and developing their skills. All comments here are expected to keep to our community guidelines


How do I share my own solutions?

  • If you completed the project off-platform, you can upload your project to your own GitHub and share the public link on the relevant project topic.
  • If you completed the project in the Codecademy learning environment, click on “Tools” and use the create a gist button, and then share that link here.

Do I really need to get set up on GitHub?
Yes! Both of these sharing methods require you to get set up on GitHub, and trust us, it’s worth your time. Here’s why:

  1. Once you have your project in GitHub, you’ll be able to share proof of your work with potential employers, and link out to it on your CV.
  2. It’s a great opportunity to get your feet wet using a development tool that tech workers use on the job, every day.

Not sure how to get started? We’ve got you covered - read this article for the easiest way to get set up on GitHub .

Best practices for asking questions about the sample solution

  • Be specific! Reference exact line numbers and syntax so others are able to identify the area of the code you have questions about.

My version using MUI

Tutorial:

Resolving the CORS Issue and Setting Up Environment Variables

After facing a series of errors (quite a lot of errors, actually), I managed to find a robust solution to the CORS (Cross-Origin Resource Sharing) issue I was experiencing while trying to consume the Yelp API in my React project. In this tutorial, I will detail how I set up an Express server to handle requests to the Yelp API, and how I structured my development environment to keep my API key secure.

Project Structure:

I created a folder named server at the root of my project, inside of which I placed two files: server.mjs and .env.

Directory:

- server
  - server.mjs
  - .env

Configuring the Express Server:

  1. Module Installation:
    First, we need to install the necessary modules. In the terminal, run the following command:

    npm install express node-fetch cors dotenv
    
  2. File server.mjs:

    import dotenv from 'dotenv';
    import express from 'express';
    import fetch from 'node-fetch';
    import cors from 'cors'; 
    
    dotenv.config();
    
    const app = express();
    
    app.use(cors()); 
    
    app.get('/yelp/businesses/search', async (req, res) => {
      const { term, location, sort_by } = req.query;
    
      try {
        const response = await fetch(
          `https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}&sort_by=${sort_by}`,
          {
            headers: {
              Authorization: `Bearer ${process.env.REACT_APP_API_KEY}`,
            },
          },
        );
    
        const data = await response.json();
        res.json(data);
      } catch (error) {
        console.error(error);
        res.status(500).send('Internal Server Error');
      }
    });
    
    app.listen(3001, () => {
      console.log('Server is running on port 3001');
    });
    

    Here, I created an Express server that listens on port 3001 and has an endpoint that redirects requests to the Yelp API. I used the node-fetch module to make the HTTP request, and cors to handle CORS.

  3. File .env:

    REACT_APP_API_KEY=your_api_key_here
    

Configuring the Front-end:

  1. File Yelp.js:
const apiKey = process.env.REACT_APP_API_KEY;

const Yelp = {
  search(term, location, sortBy) {
    return fetch(
      `http://localhost:3001/yelp/businesses/search?term=${term}&location=${location}&sort_by=${sortBy}`,
      {
        headers: {
          Authorization: `Bearer ${apiKey}`,
        },
      },
    )
      .then((response) => {
        if (!response.ok) {
          return response.json().then((errorResponse) => {
            console.error('API error:', errorResponse);
            throw new Error('API error');
          });
        }
        return response.json();
      })
      .then((jsonResponse) => {
        if (jsonResponse.businesses) {
          return jsonResponse.businesses.map((business) => {
            return {
              id: business.id,
              imageSrc: business.image_url,
              name: business.name,
              address: business.location.address1,
              city: business.location.city,
              state: business.location.state,
              zipCode: business.location.zip_code,
              category: business.categories[0]?.title,
              rating: business.rating,
              reviewCount: business.review_count,
            };
          });
        } else {
          console.log('No businesses found', jsonResponse);
        }
      })
      .catch((error) => {
        console.error('Error fetching and parsing data', error);
      });
  },
};

export default Yelp;

After these configurations, my Express server serves as an intermediary between the front-end and the Yelp API, handling CORS and keeping my API key secure through the use of environment variables. This approach helped me overcome the challenges after hours facing this problem and I hope it can help other developers who might be facing similar issues.

Remember to place the .env file in the .gitignore file if you are going to upload it to GitHub to keep your API key secure.

Live: https://revenouss.netlify.app/
Repository: GitHub - felpsg/ravenous

Here’s the latest commit for my project part #3. That event handler stuff was hard, I kinda forgot all about it, and even harder, because I use React Boostrap Elements vs normal HTML elements, so I had to read a bit.

Anyway, I’m sharing a good read:

Use state documentation is good because it has some event handling example with react use case.

THX YOU SO MUCH!

This server implementation helped me so much.

You should add that to run need,
you need to do this.
npm start → start react app server
node server.mjs` → start express cors server

As for Codecademy, please add this as part of the react project? This is really useful.
Heroku solution is cool, but this is reusable!!!