1

My Heroku app fetches data from a "products" table in my database to display on my shop page. When I deploy the app on Heroku, the shop page isn't rendering the products. I'm not seeing any errors, the data is just not being displayed.

It works perfectly in my local environment even when I connect it with my Heroku Postgres database. So I know that the Heroku Postgres database has the correct data in it. I can't tell where the issue is when it's deployed to Heroku. Here are the relevant parts of my code:

// db/index.js

const { Pool } = require('pg');
require('dotenv').config();

const proConfig = {
  connectionString: process.env.DATABASE_URL,
  ssl: {
    rejectUnauthorized: false,
  }
}

const pool = new Pool(proConfig);

module.exports = {
    query: (text, params, callback) => {
      return pool.query(text, params, callback)
    }
};
// api/server.js 

require('dotenv').config();
const express = require("express");
const cors = require("cors");
const path = require("path");
const app = express();
app.use(cors());
app.use(express.json());
const port = process.env.PORT || 5000;

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

const contactRouter = require('./contactRouter');
app.use("/contact", contactRouter);

const productsRouter = require('./productsRouter');
app.use("/products", productsRouter);

app.listen(port, () => console.log(`Listening on port ${port}`));
// api/productsRouter.js

const express = require("express");
const productsRouter = express.Router();
const db = require('../db/index');
  
productsRouter.get('/', (req, res) => {
    db.query('SELECT * FROM products', (err, result) => {
        if (err) throw err;
        res.send(result.rows);
    })
});

module.exports = productsRouter;
// storeItemsSlice.js

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

export const fetchItems = createAsyncThunk('storeItems/fetchItems', 
    async () => {
        let response = await fetch('/products');
        let jsonResponse = await response.json();
        return jsonResponse;
    }
);

export const storeItemsSlice = createSlice({
    name: 'storeItems',
    initialState: {
        items: [],
        isLoading: false,
        hasError: false,
        loaded: false
    },
    extraReducers: 
        (builder) => {
            builder
                .addMatcher(
                    (action) => action.type.endsWith('/pending'),
                    (state, action) => {
                        state.isLoading = true;
                    }
                )
                .addMatcher(
                    (action) => action.type.endsWith('/fulfilled'),
                    (state, action) => {
                        state.items = [];
                        state.items = action.payload;
                        state.loaded = true;
                        state.isLoading = false;
                    }
                )
                .addMatcher(
                    (action) => action.type.endsWith('/rejected'),
                    (state, action) => {
                        state.isLoading = false;
                        state.hasError = true;
                    }
                )
        }
});

export const selectItems = (state) => state.storeItems.items;
export const selectLoaded = (state) => state.storeItems.loaded;

export default storeItemsSlice.reducer;
// Shop.js

import React, { useEffect } from 'react';
import './Shop.css';
import { StoreItem } from '../../components/StoreItem/StoreItem';
import { useDispatch, useSelector } from 'react-redux';
import { fetchItems, selectItems, selectLoaded } from '../../components/StoreItem/storeItemsSlice';

export const Shop = () => {
    const dispatch = useDispatch();
    const storeItems = useSelector(selectItems);
    const hasLoaded = useSelector(selectLoaded);
    
    useEffect(() => {
        dispatch(fetchItems());
    }, [dispatch]);

    return (
       <div className='shop-container'>
            {hasLoaded && storeItems.map((item, index) => {
                return <StoreItem item={item} key={index} />;
            })}
       </div>
    )
};

export default Shop;

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.