4

I am trying to render an html response from an API in React.

I think the problem can be that I am not handling the async fetch correctly. I am not sure if the html string I am fetching from the BE is a promise or a string. When I log it below I get a Promise

I used the code from this answer to use dangerouslySetInnerHTML to render the html though I am not sure if this is the right way to render a complete page. The backendHtmlString is a complete page that I would just like to add to React.

App.js - React code to render html:

async function createMarkup() {
  let response;
  response = await fetch(`http://localhost:8000/backed_api/html_response/?user_email=chriss%40comtura.ai`)
  const backendHtmlString = response.text()

  console.log(backendHtmlString)
  return {__html: backendHtmlString};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

function App() {
  return (
    <div className="App">
      <MyComponent/>
    </div>
  );
}

export default App;

Index.js


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
reportWebVitals();
2
  • 1
    Store the html in a useState field after receiving it, and use a useEffect callback to send the request. Currently you're sending the request on every single render... Commented Apr 11, 2022 at 13:12
  • 2
    You need to await the response.text() call to get the actual response text Commented Apr 11, 2022 at 13:15

1 Answer 1

6

Async functions always return a Promise! Make sure you resolve it to get the data.

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Since, the data is fetched from the backend, it may take some time. You can use useEffect to make the request and set the value you get from the server using useState.

function MyComponent() {
    
      const [html, setHTML] = useState({__html: ""});
    
      useEffect(() => {
        async function createMarkup() {
          let response;
          response = await fetch(`http://localhost:8000/backed_api/html_response/?user_email=chriss%40comtura.ai`)
           const backendHtmlString = await response.text()
    
           console.log(backendHtmlString)
            return {__html: backendHtmlString};
         }
         createMarkup().then(result => setHTML(result));
      }, []);
      
    
      return <div dangerouslySetInnerHTML={html} />;
    }

Also, check out this scenario. It could be another case similar to yours.

Sign up to request clarification or add additional context in comments.

4 Comments

In my case, API response an HTML page, with a lot of links (jquery, other packages) . dangerouslySetInnerHTML can not load the jQuery and other scripts, what should i do?
dangerouslySetInnerHTML will not work well in this case. You should either - make API to respond the list of scripts and inject it using useScripts or react-helmet. - or parse HTML in the response and extract script tags and do the first one. Refer: stackoverflow.com/a/64815699/11566161
can i write the response in a .html file on the fly and store it in public folder , then render it on iframe ?
Yes, not sure if any other way there.. :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.