Can't Build Gatsby With UseAxios, It Raise Error : UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80

Viewed 290

This is my 404.tsx page component, Hi, I'm having a problem when building gatsby withgatsby build always getting this error, FYI I use axios-hooks , how to solve this please?, but it works fine while development

import React from 'react';
import { Container, Box, Typography, makeStyles, Grid, useMediaQuery, useTheme } from '@material-ui/core';
import { Helmet } from 'react-helmet';
import { Link } from 'gatsby';
import useAxios from 'axios-hooks';


export default function NotFound404() {
    const [{ data: latestArticles = {}, loading: loadingLatestArticles }] = useAxios({
        baseURL: process.env.REACT_APP_API_ENDPOINT,
        url: 'latest-articles',
    });

return (
    <Box>
        
    </Box>
);

}

1 Answers

Try wrapping it inside a this condition:

import React from 'react';
import { Container, Box, Typography, makeStyles, Grid, useMediaQuery, useTheme } from '@material-ui/core';
import { Helmet } from 'react-helmet';
import { Link } from 'gatsby';
import useAxios from 'axios-hooks';


export default function NotFound404() {
    if(typeof window !=="undefined"){
    const [{ data: latestArticles = {}, loading: loadingLatestArticles }] = useAxios({
        baseURL: process.env.REACT_APP_API_ENDPOINT,
        url: 'latest-articles',
    });
    }
return (
    <Box>
        
    </Box>
);

Note: define as empty your variables outside the condition and override it inside it if needed.

but it works fine while development

Usually when something works in gatsby develop but not in gatsby build if because of the availability of global objects, such as window or document. You need to keep in mind that gatsby develop occurs in the browser while gatsby build occurs in the Node server (where there are no global objects because they are not defined yet), so the code will behave differently in both environments. This condition:

if(typeof window !=="undefined")

Will ensure that the code is rendered in the browser, avoiding being triggered in the server.

Related