React Component Not Re-Rendering When State Changes

Component is not re rendering when state is changed in react

Working app https://codesandbox.io/s/jovial-pascal-kww85?file=/src/App.js

Note:

  1. Prop name cannot be key as this name is reserved to uniquely identify component.(I have used apikey as name)
    <Display  apikey={key} placeName={placeName} />
  2. In Navbar you have to use another state to track of input in textbox.
    const  [input, setInput] =  useState("");
  3. In Navbar it should be onClick={() => props.setPlaceName(input)}
    value={input}
    onChange={(e) => setInput(e.target.value)}
  4. Form element on Submit prevent Default to not refresh page.
    <form  className="d-flex"  onSubmit={(e) =>  e.preventDefault()}>
  5. In Display call useEffect when props.placename changes.
    useEffect(async  ()  =>  {

    getWeatherInfo();

    }, [props.placeName]);

Component not re-rendering when updating state within map function

Your code is not working because const newFoobar = foobar;, the previous state and new state is same object so the component will not re-render. So you have to create a new object and update it

const update = () => {
const newFoobar = [...foobar];
newFoobar.push({
description: "This new item should render in view",
date: "asdf",
});
setFoobar(footer);
};

One Component not re-rendering on state change while other is not

You only call RecreateDataArray when the component mounts, not when props change.

That's why it doesn't update when your props change.

You could do that update with a componentWillUpdate lifecycle method, but it will be a lot easier to just refactor to a function component and use the useEffect hook instead:

import React from "react";
import Chart from "react-google-charts";
import { getScrtProvider } from "../../apis/scrt";

async function RecreateDataArray(assets) {
const wallet = await getScrtProvider();

let dataArray = [];
let total = assets.length;
let i;
dataArray.push(["symbol", "value"]);
for (i = 0; i < total; ++i) {
if (assets[i].address !== wallet.address) {
continue;
}
let totalValue = assets[i].current_price * assets[i].quantity;
dataArray.push([assets[i].symbol, totalValue]);
}
return dataArray;
}

function CryptoPieChart({ Assets }) {
const [chartData, setChartData] = React.useState([]);
React.useEffect(() => {
RecreateDataArray(Assets).then(setChartData);
}, [Assets]);

return (
<Chart
width={"300px"}
height={"300px"}
chartType="PieChart"
loader={<div>Loading Chart</div>}
data={chartData}
options={{
legend: "none",
pieSliceText: "label",
colors: [
"#024678",
"#8accfd",
"#7CB7E3",
"#6EA3CA",
"#608EB1",
"#527A97",
"#45657E",
"#375165",
],
backgroundColor: {
fill: "#000000",
fillOpacity: 0.0,
},
}}
rootProps={{ "data-testid": "5" }}
/>
);
}

export default CryptoPieChart;


Related Topics



Leave a reply



Submit