Search code examples
node.jsreactjsmongodbherokuaxios

React backpress prints axios response on the screen


I've created a React App, which works fine, but the issue is, when I click the back button, the screen goes white and prints the response of the axios get or post request.

Here is my useEffect:

useEffect(() => {
        async function loadIBooks() {
            const response = await axios.get(
                `/Bookss?_type=${BooksType}&_page=${page}`
            );

            setBookss(response.data.data);

            if (response.data.data.length === 0) {
                setNoBookss(true);
            } else setNoBookss(false);
            setLoading(false);
        }
        loadBookss();
    }, [page, BooksType]);

And this is my route's data:

router.get("/books", async (req, res) => {
    const allbooks = await bookSchema
        .find({
            status: "Published",
            bookType: req.query._type,
        })
        .sort({ _id: -1 });

    res.json({
        data: allbooks,
        status: res.status,
    });
});

It first shows data correctly, but when I go to next page, and come back, it prints the axios response.


Solution

  • I sorted this issue by adding the static part in the server.js

    if (process.env.NODE_ENV == "production") {
        app.use(express.static("./client/build"));
        const path = require("path");
        app.get("*", (req, res) => {
            res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
        });
    }