Skip to content

fetch returning undefined rather than result #202

Open
@DoryZi

Description

@DoryZi

I have a create react app project.
With the following component:

const LegalPage: React.FC = () => {
  const classes = useStyles()
  const { documentType } = useParams<{documentType: string}>()
  const [content, setContent] = useState<string>()

  const {t, i18n} = useTranslation()
  useEffect(() => {
    const loadFile = async () => {
      try {
      const response = await fetch(`/legalDocs/${i18n.language}/${documentType}.html`)
      const htmlContent = (response.status === 200) ? await response.text() :
        (`<p>Error reading ${documentType}. please try again, if issue persists please let us know at [email protected]</p>`)
      setContent(htmlContent)
      } catch (e) {
        console.error(e)
        setContent(`<p>Error reading ${documentType}. please try again, if issue persists please let us know at [email protected]</p>`)
      }
    }
    loadFile()
  }, [documentType, i18n.language])
  return (<Container className={classes.root}>
      <Typography variant="body1">
        {(content) ? parse(content) : ''}
      </Typography>
  </Container>
  )
}

export default LegalPage

I have setupTests.ts

// setupTests.ts
import jestFetchMock from 'jest-fetch-mock'
jestFetchMock.enableMocks()

the and test:
const enTermsOfUse = '

TermsOfUse
'

fetch.mockResponse({
  status: 200,
  text: () => Promise.resolve(enTermsOfUse)
})

test('loading privacy policy in bulgaria works ok ', async () =>{

  htmlContent = bgPrivacyPolicy
  param = 'privacy-policy'
  render(<LegalPage />)
})

How the await fetch in the LegalPage always returns undefined.
Am I doing something wrong or is there a bug?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions