Chartjs-React Chart.js Match API data to what Title is displaying, then update chart on data/Title change

1πŸ‘

βœ…

It seems like you need to sync the jobId state between the TitleCycle component and the LineChart component, so that both has access to this variable, and can render stuff in sync (Title changes and LineChart changes also).

In that case, you need jobId as a somewhat global variable. I think of this solution.

This seems to be the current hierachy

App
|-- LineChart
|-- Title
    |-- TitleCycle

Therefore, put the jobId in the common ancestor and prop drills it down. In this case, instead of generating jobId and index from TitleCycle and having to lift the state back up and around into LineChart, you shall cycle the indexes right inside App.js. Something like this:

// App.js
function App() {
    const [allData, setAllData] = useState([]);
    const [index, setIndex] = useState(0);

    // Fetch all data, all jobs
    useEffect(() => {
        function fetchData() {
            let body = {
                from: "bpz99ram7",
                select: [3, 6, 40],
                where: "{40.CT. 'In Progress'}",
                sortBy: [{ fieldId: 6, order: "ASC" }],
                groupBy: [{ fieldId: 40, grouping: "equal-values" }],
                options: { skip: 0, top: 0, compareWithAppLocalTime: false },
            };

            fetch("https://api.quickbase.com/v1/records/query", {
                method: "POST",
                headers: headers,
                body: JSON.stringify(body),
            })
                .then((response) => response.json())
                .then(({ data }) => setAllData(data));
        }
        fetchData();
    }, []);

    // Cycle through the jobIds and indexes
    useEffect(() => {
        const timerId = setInterval(
            () => setIndex((i) => (i + 1) % allData.length),
            5000 // 5 seconds.
        );
        return () => clearInterval(timerId);
    }, [allData]);

    // Calculate info based on index
    const jobId = allData[index]?.["3"]?.value || "290"; // Default "290"
    const title = allData[index]?.["6"]?.value || "Default title"; 

    // Renders the components with the necessary data
    return (
        <div>
            <Title title={title} />
            <LineChart1 jobId={jobId} />
            <LineChart2 jobId={jobId} />
        </div>
    );
}

// LineChart.js
function TotalLineChart(props) {
    // Got the jobId from props
    const { jobId } = props;

    // Now make the request with this jobId
}

Leave a comment