0

I am trying to get dataURI for an image using ApexCharts.exec method, here is my code:

const getDataURI = async() => {

  console.log('leftChartObj', leftChartObj) // gets the data required correctly - essentially an object which is used in the next line; so leftChartID is assigned the value as expected.

  const leftChartID = leftChartObj.props.options.chart.id;

  ApexCharts.exec(leftChartId, 'dataURI' , {scale:1.08}).then(  
  ( async ({imgURI}) => {
     await setSvgLeft(imgURI);          // These methods are inbuilt and I guess async/await isn't needed but I was just trying out.
 
     console.log('svgLeft', svgLeft) // state variable that is set in the above line =
  })
  );

  console.log('method ended', svgLeft) 

}


And this is the output I get:

leftChartObj { 'props': {...}, 'context': {...} , .. } - as expected

method ended null

svgLeft  null

I understand that the code is exiting before the variable is set, then tried async/await. But that didn't help either.

Also, this function is called upon a button click in the UI, if the click the button for the second time everything works as expected.

iNam524
  • 68
  • 7
  • Don't mix `await` with `.then()`, it just makes your code confusing. Also, your comments are using the wrong slashes, should be `//` – Phil Apr 18 '23 at 03:49
  • Thank you for the suggestion, changed the question prompt. – iNam524 Apr 18 '23 at 03:52
  • You're still mixing `await` with `.then()`. I strongly suggest you completely avoid such a pattern – Phil Apr 18 '23 at 04:17
  • Is `setSvgLeft` a state setter? If so, this is a common mistake which can generally be solved by not relying on `console.log()` to test state – Phil Apr 18 '23 at 04:19

1 Answers1

0

In React's hook, you need to use useEffect to reach your prompt.
Something like this:

const getDataURI = async() => {

  const leftChartID = leftChartObj.props.options.chart.id;

  ApexCharts.exec(leftChartId, 'dataURI' , {scale:1.08}).then(  
  ( ({imgURI}) => {
     setSvgLeft(imgURI);
 
  })
  );

}

useEffect(() => {
  console.log('svgLeft', svgLeft) // This line will run whenever `svgLeft` change
}, [svgLeft])

mikenlanggio
  • 1,122
  • 1
  • 7
  • 27
  • I do see the correct values when this useeffect is triggered, however, in the original method that called 'getDataURI' the required values are still 'null'. So basically we are exiting the 'getDataURI' method before even reaching the place where is set the state variable. – iNam524 Apr 18 '23 at 04:12
  • As I told you. You cannot. You HAVE TO use `useEffect`, no other way to reach in `getDataURI`. You can use `imgURI` directly inside `getDataURI` instead of `svgLeft` – mikenlanggio Apr 18 '23 at 09:46