0

I need to use a function that I received from a fetch call, therefore, the entire function (or functions received from the call are in string). I have seen many posts about the usage of eval. I think it is safe for me to use because the fetch calls are going to my website. Here is what I want to achieve :

var f = "function jsFunction(){console.log('test');}";
eval(f);
jsFunction();

I have seen examples of this working online but mine doest not seem to work, I have the error : 'jsFunction' is not defined.

I am using React to make a Teams application so this may explain why the eval does not work, I have tested this code in a jsfiddle and it worked.

This would be the first part of my problem, because in reality the fetch call returns html and js, and (I think) I want the html to be rendered and then the js to be read. I managed to read the html using dangerouslySetInnerHTML but it does not work for the js.

Do I need 2 components ? One to render the HTML and then one to run the js ? Thanks

  • I'd suggest that the approach you're using is incorrect. You can load JS script from a `fetch` call, but you should never, ever use `eval` to execute it. See the duplicate for more information on the better approach. – Rory McCrossan Jul 11 '23 at 13:37
  • `in reality the fetch call returns html and js, and (I think) I want the html to be rendered and then the js to be read` in this case either split the pages and make separate calls, or if that's not possible, then extract one content from the other and apply the method linked to in the dupe – Rory McCrossan Jul 11 '23 at 13:39
  • The first option would be really tedious server side, but I do not understand what the second method consists of. So first I put html and js in different variables ? But then the method (the one written in js ?), link and dupe I do not know what this means... Sorry – Jacques Célère Jul 11 '23 at 13:51

0 Answers0