Search code examples
javascripthtmlreactjsaxiosget

Need to retrieve html from axios request


I am using axios to send a request to a resource that is exposing html on the backend. When I send the GET request I receive an object as a response. When I print the response with console.log() it breaks the React application due to the response being an object and not the html I am expecting.

Currently I am trying to specify responseType: 'document' in the config. But that doesn't seem to work. I still get an object with the error being:

"Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."

Ultimately I need to end up with a <div></div> that I can embed in my React page.

import axios from 'axios';

const examplePage = "example.com/example"

export const requestExamplePage = async () => {
    const {data} = await axios.get(examplePage, {responseType: 'document})
    
    return data
}

Solution

  • The error:

    "Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."
    

    Actually means that you're trying to render a promise. Are you sure thats the right way of destructuring the request? data has to be a html wrapped in double quotes (string) and you also need dangerouslySetInnerHtml to inject it into a div.

    Try this:

    export const requestExamplePage = async () => {
        const {data} = await axios.get(examplePage, {responseType: 'document'})
        
        return (
            <div dangerouslySetInnerHTML={{ __html: data }} />
        )
    }
    

    Make sure that data is an an actual html string.