swartchris8
swartchris8

Reputation: 720

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();

Upvotes: 4

Views: 28378

Answers (1)

Shri Hari L
Shri Hari L

Reputation: 4894

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.

Upvotes: 6

Related Questions