Welcome to Using APIs LikePro! This project demonstrates advanced techniques for working with APIs in React, focusing on fetching and displaying product data. It includes best practices for handling API requests, managing state, and ensuring smooth dynamic rendering of data.
- Dynamic Product Search: Search for products in real-time using a search input.
- Custom Hook for API Requests:
useCustomQuery
hook that abstracts API calls and manages loading, error, and data states. - Error Handling: Graceful handling of errors during data fetching.
- Efficient State Management: Using React hooks to manage state and re-fetching of data when necessary.
- CORS Fixing: Handled CORS policies to make the API work across different environments.
- Frontend: React, Axios
- Backend: Express (For CORS handling)
- API: Fetching product data from an API
To get this project up and running on your local machine, follow these steps:
git clone https://github.com/your-username/using-apis-likepro.git
Navigate to the project directory and install the required dependencies:
cd using-apis-likepro
npm install
To start the frontend project (React app), run:
npm start
For the backend API, ensure that your Express server is running.
A custom hook that encapsulates the logic for making API calls, including error handling, data fetching, and loading states.
const fetchProducts = (signal) => getProductBySearch(search || "", signal);
const {
data: products,
error,
loading,
} = useCustomQuery(fetchProducts, [search]);
- Signal: Used to cancel the fetch request if necessary (e.g., on unmount).
- Search: Dynamically fetches products based on the search query.
A helper function that fetches data from the backend API.
export const getProductBySearch = (productName) =>
api.get(`/products?search=${productName}`, {
signal: controller.signal,
});
This function uses the search query to fetch product data from the API and handles the cancellation signal.
If you want to run the backend API locally, make sure you have the following:
- Express: For handling API requests.
- CORS Middleware: To allow cross-origin requests.
Example CORS configuration:
const cors = require("cors");
app.use(cors());
Make sure the server is running on the appropriate port (e.g., http://localhost:3000
).
We welcome contributions to make this project better! If you have suggestions or improvements, feel free to fork the repo, make your changes, and create a pull request.
This project is open-source and available under the MIT License.