Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering html response from API in React

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();
like image 707
swartchris8 Avatar asked Oct 28 '25 06:10

swartchris8


1 Answers

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.

like image 160
Shri Hari Avatar answered Oct 31 '25 11:10

Shri Hari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!