简体   繁体   中英

Dynamically loaded chart data not showing Chartjs React

I created a pie chart that shows the pokemon catch rate. The console.logs all work at first but then it appears to continue running so the data is no longer displaying correctly. The props value is a useState variable from a different component.

Here is my code:

const [captureRate, setCaptureRate] = useState();
// const [lossRate, setLossRate] = useState();

console.log("run");



    let capture=[];
    let notCapture=0;
    console.log((props.nameForRate));

    useEffect(() => {
    axios.get('https://pokeapi.co/api/v2/pokemon-species/'+(props.nameForRate)+'/')
    .then((res)=>{

      let data=res.data;

      capture[0] = data.capture_rate;
      capture[1] = 255 - (data.capture_rate);
    
      console.log(("it works " +capture));
      setCaptureRate(capture);

    });

    
    console.log("here it is again " + captureRate[0]);
    
  
   }, []);




return(
    <>
    <div className="componentInteriorDoughnut">
          {/* <h3>Chart 2: Doughnut Chart</h3> */}

          <div className="CaptureRate">
          <Doughnut 
          data={{
             
              labels: ['Captured', 'Not Captured'],
              datasets: [{
                  label: 'Capture Rate',
                  data: captureRate,
                  backgroundColor: [
                    'rgb(42, 157, 143)',
                    '#f1f1f1',
                   
                  ],
                
                  borderWidth: 0,
                //   borderRadius:10,
                  
            
                  
                  
              },
              

Can you try adding listener to specific value change, this function will invoke on every state changes. instead of below code

useEffect(() => {},[])

Instead of that if you can specify which variable to listen, then multiple function call can be avoidable. For example use like this

useEffect(() => {},[notCapture]);

In this scenario if there is any change happens to notCaputure variable, then only function got triggered

Please check the below code. It may help you.

const finalData = () => {
        return new Promise((resolve, reject) => {
            const data = {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                datasets: [{
                    label: 'My First dataset',
                    data: actionsListData.map(({ EditorId }) => EditorId)
                }]
            }
            resolve(data)
        })
    }

<ChartControl
            type={ChartType.Bar}
            datapromise={finalData()}
        />

Please refer below link for details

https://pnp.github.io/sp-dev-fx-controls-react/controls/ChartControl/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM