Search code examples
javascriptreactjscreate-react-appes6-modules

How to use the function from the js file returned by an API in react?


I've been using create-react-app

This is the sample request in the componentDidMount():

axios.get("/")
  .then(res => {
    const test = res.data;
  })
  .catch(err => console.log(err));

I want to use the response of the API which is a javascript code.

Here's the sample return of the API:

const sample = props => (React.createElement('div'))

What I'm trying to achieve is to use the sample function and pass data to it and make it display in the current component

render() {
  return test.sample(SomeData)
}

Solution

  • It seems very wrong to do that, but you can use eval on the response:

    eval(res.data);
    

    Here is a write-up on why you should never use eval.