reactjs – Plotly.js component not re-rendering in React when state changes
I’m using react-plotly.js to render a plot in my React application. I have a Zustand store to manage the state of my plot data and layout. When I click a button to fetch new data and update the state, the Plot component does not re-render with the new data. Here is my setup:
store.js
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
const useStore = create(immer((set) => ({
data: [
{
x: [1, 2, 3, 4, 5],
y: [2, 6, 3, 8, 5],
type: 'bar',
marker: { color: 'blue' },
},
],
layout: {
width: 700,
height: 400,
title: 'A Different Plot',
},
setData: (newData) => set((state) => {
console.log("Updating data:", newData);
state.data = newData;
}),
setLayout: (newLayout) => set((state) => {
console.log("Updating layout:", newLayout);
state.layout = newLayout;
}),
})))
export default useStore
App.jsx
import { useEffect } from 'react'
import Plot from 'react-plotly.js'
import useStore from './store'
import './App.css'
function App() {
const data = useStore(state => state.data)
const layout = useStore(state => state.layout)
const setData = useStore(state => state.setData)
const setLayout = useStore(state => state.setLayout)
const fetchData = async () => {
console.log("Fetching data...");
const fakeData = [
{
x: [1, 2, 3, 4, 5],
y: [2, 6, 3, 8, 5],
type: 'bar',
marker: { color: 'blue' },
},
];
const fakeLayout = {
width: 700,
height: 400,
title: 'A Different Plot 5',
};
setData(fakeData);
setLayout(fakeLayout);
console.log("Data fetched and set:", { fakeData, fakeLayout });
};
useEffect(() => {
if (data && layout) {
console.log("Data and layout are ready!");
}
}, [data, layout]);
return (
<>
{data && layout ? (
) : (
Loading...
)}
>
)
}
export default App
I have tried adding a key prop to the Plot component to force it to re-render, but it still doesn’t update with the new data. What am I missing? How can I ensure that the Plot component re-renders when the state changes?
Read more here: Source link
