TypeError: _service_api_js__WEBPACK_IMPORTED_MODULE_1__.api.userSignUp is not a function

Issue

This Content is from Stack Overflow. Question asked by Subhash kumar

I have a backend that store the information about the users. I am trying to post some required user input with a module in services/api.js.

This is my Login page from where i am making a post request;

import React from 'react'
// Material UI
import { Box, TextField, Button, styled, Typography } from "@mui/material"


// Hooks
import { useState } from 'react'
// Importing API
import { api } from '../../service/api.js'


const Components = styled(Box)`width:400px;
margin:auto;
box-shadow:5px 2px 5px 2px rgb(0,0,0,0.6)
`
const Images = styled('img')({
    width: 100,
    margin: 'auto',
    display: 'flex',
    padding: '50px 0'

})

const Wrapper = styled(Box)`
padding:25px 35px;
display:flex;
flex:1;
flex-direction:column;
& > div, &>Button{
    margin-top:20px;

}
`
const LoginButton = styled(Button)`
     text-transform:none;
     background:#bb041b;
     color:#fff;
     height:40px;
     border-radius:2px;

`
const SignButton = styled(Button)`
    text-transform:none;
     background:#fff;
     color:#2874fe;
     height:40px;
     border-radius:2px;
     box-shadow:0 2px 4px 0 rgb(0,0,0,15%) 
`
const Text = styled(Typography)`
   color:#878787;
   font-size:14px;
   
   `

const signUpIntialValues = {
    name: '',
    username: '',
    password: '',
}

const Error = styled(Typography)`
font-size:10px;
color:#ff6161;
line-height:0;
margin-top:10px;
font-weight:600;

`

const Login = () => {

    const [account, toggleAccount] = useState('Login')
    const imageURL = 'https://www.sesta.it/wp-content/uploads/2021/03/logo-blog-sesta-trasparente.png';
    const [signup, setSignUp] = useState(signUpIntialValues);
    const [error,setError]=useState('')
    const toggleSignUp = () => {
        account === 'signup' ? toggleAccount('Login') : toggleAccount('signup');
    }

    const onInputChange = (e) => {
        setSignUp({ ...signup, [e.target.name]: e.target.value });
    }


    const signupUser = async () => {
        let response = await api.userSignUp(signup)
        if (response.isSuccess) {
            setError('')
            setSignUp(signUpIntialValues);
            toggleAccount('login');
        } else {
            setError("Something went wrong please try again later")
        }
    }
    return (
        <Components>
            <Box>
                <Box>
                    <Images src={imageURL} alt="image" />
                </Box>
                {
                    account === 'Login' ?
                        <Wrapper>
                            <TextField id="filled-basic" label="Enter username" variant="standard" />
                            <TextField id="filled-basic" label="Enter password" variant="standard" />
                            <LoginButton variant="contained">Login</LoginButton>
                            <Text style={{ textAlign: 'center', padding: 2 }}>OR</Text>
                            <SignButton onClick={() => toggleSignUp()}>CREATE AN ACCOUNT </SignButton>
                        </Wrapper>
                        :
                        <Wrapper>
                            <TextField id="filled-basic" label="Enter Name" variant="standard"
                                onChange={(e) => onInputChange(e)} name='name'
                            />
                            <TextField id="filled-basic" label="Enter username" variant="standard"
                                onChange={(e) => onInputChange(e)} name='username'
                            />
                            <TextField id="filled-basic" label="Enter password" variant="standard"
                                onChange={(e) => onInputChange(e)} name='password'
                            />
                            {error && <Error>{error}</Error>}
                            <SignButton onClick={() => signupUser()} variant="text">Sign Up</SignButton>
                            <Text style={{ textAlign: 'center', padding: 2 }}>OR</Text>
                            <LoginButton variant="contained" onClick={() => toggleSignUp()}>Already have AN ACCOUNT </LoginButton>
                        </Wrapper>

                }

            </Box>

        </Components>
    )
}

export default Login

This is my API:-

import axios from 'axios';
import { API_NOTIFICATION_MESSAGES } from '../config/config.js';
import SERVICE_URLS from '../config/config'

const API_URL = "http://localhost:8000";
const axiosInstance = axios.create({
    baseURL: API_URL,
    timeout: 10000,
    headers: {
        "content-type": "application/json"
    }
})


// Making the interceptor using axios instance

axiosInstance.interceptors.request.use(
    function (config) {
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
)

axiosInstance.interceptors.response.use(
    function (response) {
        // Stop the loader here
        return processResponse(response)
    },
    function (error) {
        // Stop the global Loader here
        return Promise.reject(processError(error))
    }
)

/////////////////////////////////////////////////////////////////////////
// if success-> return (isSuccess:true,data: object)
// if fail-> return(isFailure:true,status:string,msg:String,code:int)


const processResponse = (response) => {
    if (response?.status === 200) {
        return ({ isSuccess: true, data: response.data })
    } else {
        return ({
            isFailure: true,
            status: response?.status,
            msg: response?.msg,
            code: response?.code,
        })
    }
}




/////////////////////////////////////////////////////////////////////////
// if success-> return (isSuccess:true,data: object)
// if fail-> return(isFailure:true,status:string,msg:String,code:int)
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

const processError = (error) => {
    if (error.response) {
        // Request made and server responded with a status other that fails out of the range 2xx;
        console.log("Error in response", error.toJSON());
        return {
            isError: true,
            msg: API_NOTIFICATION_MESSAGES.responseFailure,
            code: error.response.status
        }
    } else {
        if (error.request) {
            //  Request made but no response was rececived.
            console.log("Error in request", error.toJSON());
            return {
                isError: true,
                msg: API_NOTIFICATION_MESSAGES.requestFailure,
                code: ""
            }

        } else {
            // Something from the front-end or Something happened in setting up request that triggers an error. 
            console.log("Error in network", error.toJSON());
            return {
                isError: true,
                msg: API_NOTIFICATION_MESSAGES.networkError,
                code: ""
            }
        }
    }
}


const api = {};

for (const { key, value } of Object.entries(SERVICE_URLS)) {
    api[key] = (body, showUploadProgress, showDownloadProgress) => {
        axiosInstance({
            method: value.method,
            url: value.url,
            data: body,
            responseType: value.responseType,
            onUploadProgress: function (progressEvent) {
                if (showUploadProgress) {
                    let percentagecompleted = Math.round(progressEvent.loaded * 100)
                    showUploadProgress(percentagecompleted);
                }
            },
            onDownloadProgress: function (progressEvent) {
                if (showDownloadProgress) {
                    let percentagecompleted = Math.round((progressEvent.loaded * 100))
                    showDownloadProgress(percentagecompleted);
                }
            }
        })
    }
}

export { api };

This is the Config file:-

// API_NOTIFICATION_MESSAGES

 const API_NOTIFICATION_MESSAGES = {
    loading: {
        title: "Loading....",
        message:"Data is being loaded, please wait"
    },
    Success: {
        title: "Success",
        message:"Data successfully loaded"
    },
    responseFailure: {
        title: "Error",
        message:"An error occured while fetching response from the server.  Please Try Again",
    },
    requestFailure: {
        title: "Erroe",
        message:"An error occured while parsing request data"
    },
    networkError: {
        title: "Error",
        message:"Unable to connect with the server!!... Please check your internet connectivity"
    }
}

//  API SERVICE CALL
// Sample request 
// Need SERVICE CALL:(url:"/",method:"POST/GET/PUT/DELET",params:true/false, query:true/false)
  const SERVICE_URLS = {
    userSignUp:{
        url:'/signup',
        method: 'POST'
    }
}

export default SERVICE_URLS;
export {API_NOTIFICATION_MESSAGES };

When execution reaches api.userSignUp(signup) in Login Page in signupUser function, the error is thrown.

I am really confused , but here I just don’t find the problem. Thank you in advance for helping a newcomer!



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?