最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Is there any way to update or call api realtime without periodic-api-call method? - Stack Overflow

programmeradmin5浏览0评论

Recently, I have been looking for a solution for a problem. There are 2 pages, such as AddBook.jsx and ViewAllBooks.jsx. AddBook.jsx belogs to insert a new book detail, as well as ViewAllBooks.jsx belongs to show all book lists in table form. There are two separate screens used. Screen one is to add new book details, and screen two is to show all the book detail lists. The problem is, when admin adds a new book detail (from screen one), the lists of books page (screen two) needs to get updated without refreshing the browser. It means, when admin adds new book details, api needs to send the response to ViewAllBooks.jsx page to show updated book lists. Need a solution to solve this problem (can't use periodic-api-call method).

Screenshot of Add a new book

Screenshot of List of all books

Code snippet of AddBook detail

// src/components/AddBookForm.js
import React, { useState } from "react";

const AddBookForm = () => {
  const [book, setBook] = useState({
    title: "",
    author: "",
    publisher: "",
    price: "",
  });

  const handleChange = (e) => {
    setBook({ ...book, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await fetch(
        "http://localhost/reactQueryDemo/server/public/api/add-book",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(book),
        }
      );

      const data = await response.json();
      alert(data?.message);
      setBook({ title: "", author: "", publisher: "", price: "" });
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div className="max-w-md mx-auto bg-white p-6 rounded-lg shadow-md mt-10">
      <h2 className="text-xl font-semibold mb-4">Add Book Details</h2>
      <form onSubmit={handleSubmit} className="space-y-4">
        <input
          type="text"
          name="title"
          value={book.title}
          onChange={handleChange}
          placeholder="Title"
          className="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          required
        />
        <input
          type="text"
          name="author"
          value={book.author}
          onChange={handleChange}
          placeholder="Author"
          className="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          required
        />
        <input
          type="text"
          name="publisher"
          value={book.publisher}
          onChange={handleChange}
          placeholder="Publisher"
          className="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          required
        />
        <input
          type="number"
          name="price"
          value={book.price}
          onChange={handleChange}
          placeholder="Price"
          className="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          required
        />
        <button
          type="submit"
          className="w-full bg-blue-600 text-white p-2 rounded-md hover:bg-blue-700 transition"
        >
          Add Book
        </button>
      </form>
    </div>
  );
};

export default AddBookForm;

Code snippet of Show all book detail

// src/components/ViewAllBooks.js
import React, { useEffect, useState } from "react";

const ViewAllBooks = () => {
  const [books, setBooks] = useState([]);

  const fetchBooks = async () => {
    try {
      const response = await fetch(
        "http://localhost/reactQueryDemo/server/public/api/showBooks"
      );
      const data = await response.json();
      setBooks(data.books);
      console.log(data);
    } catch (error) {
      console.error(error);
    }
  };

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

  return (
    <div className="max-w-4xl mx-auto mt-10 p-6 bg-white shadow-md rounded-lg">
      <h2 className="text-xl font-semibold mb-4">All Books</h2>

      <table className="w-full border-collapse border border-gray-300">
        <thead>
          <tr className="bg-gray-200">
            <th className="border border-gray-300 p-2">#</th>
            <th className="border border-gray-300 p-2">Title</th>
            <th className="border border-gray-300 p-2">Author</th>
            <th className="border border-gray-300 p-2">Publisher</th>
            <th className="border border-gray-300 p-2">Price (LKR)</th>
          </tr>
        </thead>
        <tbody>
          {books.map((book) => (
            <tr key={book.id} className="text-center">
              <td className="border border-gray-300 p-2">{book.id}</td>
              <td className="border border-gray-300 p-2">{book.title}</td>
              <td className="border border-gray-300 p-2">{book.author}</td>
              <td className="border border-gray-300 p-2">{book.publisher}</td>
              <td className="border border-gray-300 p-2">{book.price}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default ViewAllBooks;

Tech stack is React.js, Laravel and MySQL

I've tried periodic-api-call method. But it is not suitable in realtime. The ViewAllBooks.jsx page need recieve api response, when admin adds a new book detail. This is what i am expecting. Both pages are display in seperate screens.

发布评论

评论列表(0)

  1. 暂无评论