javascriptreactjsnext.jsgetstaticprops

Can't figure out why getStaticProps isn't loading before main exported function


I am using npm run dev to debug this, which uses getStaticProps to process a number of d3 props before injecting it into the main output function at runtime. As far as I can tell, getStaticProps isn't running - a console.log inside it to retrieve keyValues doesn't return anything at all. plots isn't being loaded in the function Sidebar.

import React, { useState, useEffect, useRef } from "react";
import Papa from 'papaparse';
import { scaleLinear, quantile } from 'd3';
import { ViolinShape } from "components/ViolinShape";

const fetchData = async () => {
    // Fetch the CSV data and process it using Papa.parse
    const response = await fetch('data_csv/singapore-tess.csv');
    const reader = response.body.getReader();
    const result = await reader.read();
    const decoder = new TextDecoder('utf-8');
    const csv = decoder.decode(result.value);

    return new Promise((resolve, reject) => {
        Papa.parse(csv, {
            header: true,
            complete: function (results) {
                const output = {};
                results.data.forEach(row => {
                    for (const key in row) {
                        if (!output[key]) output[key] = [];
                        output[key].push(row[key]);
                    }
                });
                resolve(output); // resolve the Promise with the output
            },
            error: function (error) {
                reject(error); // reject the Promise if there's an error
            }
        });
    });
}

export async function getStaticProps() {
    // Fetch the data and create a dictionary of plots
    try {
        const keyValues = await fetchData();

        const plots_a = {};

        for (const key in keyValues) {
            const data = keyValues[key];
            const p5 = quantile(data.sort(), 0.05);
            const p95 = quantile(data, 0.95);
            const xS = scaleLinear().domain([p5, p95]).range([0, width]);

            plots_a[key] = {
                data,
                xScale: xS,
            };
        }

        console.log(plots_a);

        return {
            props: {
                plots: plots_a, // return plots_a here
            },
        };
    } catch (err) {
        console.error(err);
        // You can return an empty props object or some default props in case of an error.
        return {
            props: {},
        };
    }
}

const ViolinPlot = ({ width, height, variable, data, xScale }) => {
    // Render the ViolinPlot component using the provided data and xScale
    if (!data || !xScale) {
        return <div>Loading...</div>;
    }

    return (
        <svg style={{ width: width * 0.9, height: height * 2 }}>
            <ViolinShape
                height={height}
                xScale={xScale}
                data={data}
                binNumber={10}
            />
        </svg>
    );
}

const Sidebar = ({ plots, selectedCell, setSelectedCell }) => {

    const [sidebarWidth, setSidebarWidth] = useState(0);
    const sidebarRef = useRef(null);

    useEffect(() => {
        const handleResize = () => {
            const width = sidebarRef.current.offsetWidth;
            setSidebarWidth(width);
        };

        // Initial sidebar width
        handleResize();

        // Event listener for window resize
        window.addEventListener('resize', handleResize);

        // Cleanup
        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    return (
        <div ref={sidebarRef} className="sidebar shadow-md bg-zinc-50 overflow-auto">
            {Object.entries(selectedCell).map(([key, value]) => (
                <div key={key} className="p-4 border mb-4">
                    <h3 className="text-lg font-bold mb-2">{key}</h3>
                    <p>{value}</p>
                    {plots[key] && (
                        <ViolinPlot
                            width={sidebarWidth}
                            height={50}
                            variable={key}
                            data={plots[key].data}
                            xScale={plots[key].xScale}
                        />
                    )}
                </div>
            ))}
        </div>
    );
};

export default Sidebar;

Solution

  • I am see from the name that this is a Sidebar component.

    getStaticProps function is only invoked inside the page folder (i.e Pages).

    If you want to use this data in Sidebar, then move the getStaticProps function to a page where the Sidebar is imported and the pass the value to the Sidebar component as prop.