Skip to content

Latest commit

 

History

History
99 lines (85 loc) · 4.69 KB

22.Frontend-Backend-Communication.md

File metadata and controls

99 lines (85 loc) · 4.69 KB

Unlocking the Power of Full-Stack Development: A Guide to Frontend-Backend Communication

Building a modern web application requires seamless communication between the frontend and backend. The frontend, often built with technologies such as React or Angular, handles the user interface and user interactions, while the backend, typically built with technologies such as Node.js or Python, handles server-side logic and data storage. In this blog post, we will explore the various ways in which the frontend and backend can communicate and work together to create a seamless user experience. From simple HTTP requests to more advanced techniques such as WebSockets, we will take a closer look at the different methods available for frontend-backend communication and discuss their pros and cons.

import React, { useState, useEffect, useCallback } from "react";
import AddMovie from "./components/AddMovie";
import MoviesList from "./components/MoviesList";
import "./App.css";

function App() {
  const [movieData, updateMoviesData] = useState([]);
  const [isLoading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  //Get Method by default
  const fetchingMoviesHandler = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch(
        "https://react-muhib-default-rtdb.firebaseio.com/movies.json"
      );
      if (!response.ok) {
        throw new Error("Something went wrong");
      }
      const data = await response.json();
      console.log(data);
      let loadedMovies = [];
      for (const key in data) {
        loadedMovies.push({
          id: key,
          title: data[key].title,
          openingText: data[key].openingText,
          releaseDate: data[key].releaseDate,
        });
      }
      updateMoviesData(loadedMovies);
    } catch (error) {
      setError(error.message);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    fetchingMoviesHandler();
  }, [fetchingMoviesHandler]);

  async function addMovieHandler(movie) {
    const response = await fetch(
      "https://react-muhib-default-rtdb.firebaseio.com/movies.json",
      {
        method: "POST",
        body: JSON.stringify(movie),
        headers: {
          "content-type": "application/json",
        },
      }
    );
    const data = response.json();
    console.log(data);
  }

  let content = <p>Found no Movies</p>;
  if (movieData.length > 0) {
    content = <MoviesList movies={movieData} />;
  }
  if (error) {
    content = <p>{error}</p>;
  }
  if (isLoading) {
    content = <p>Loading....</p>;
  }

  return (
    <React.Fragment>
      <section>
        <AddMovie onAddMovie={addMovieHandler} />
      </section>
      <section>
        <button onClick={fetchingMoviesHandler}>Fetch Movies</button>
      </section>

      <section>{content}</section>
    </React.Fragment>
  );
}

export default App;

This code is a React functional component called "App" that is responsible for displaying and managing a list of movies. The component starts by importing the React library, along with the useState, useEffect, and useCallback hooks. It also imports two other components, "AddMovie" and "MoviesList", and a CSS file called "App.css".

The component then defines several state variables: movieData, isLoading, and error, all of which are initialized with useState. The variable movieData is an array that will store the list of movies, isLoading is a boolean that will indicate whether the app is currently loading the data, and error is a string that will hold an error message in case something goes wrong.

The component also defines a function called fetchingMoviesHandler, which is an async function that uses the Fetch API to retrieve the movie data from a remote server. The function uses the setLoading and setError state variables to update the loading status and error message accordingly. The function also uses the updateMoviesData state variable to update the movieData array.

The component then uses the useEffect hook to call the fetchingMoviesHandler function when the component is first rendered. It also define a function called addMovieHandler which is responsible for adding the movie to the remote server.

Finally, the component renders the JSX that makes up the UI of the app, displaying the "AddMovie" and "MoviesList" components, along with a button that, when clicked, will call the fetchingMoviesHandler function to refresh the movie data. It also includes some conditional logic that will display different content depending on the values of the state variables. If there's no movieData available, it will display "Found no Movies" , if there's any error it will display the error message and if isLoading is true it will display "Loading...".