0

I am new to the React world, and usage of components, I have an underlying issue where I have a Login Component that I call from App.js render().

The Login.js is having a fetch() api, which is used to fetch the response of whatever is typed on the form.

Expected Result - One time call to the fetch api, when I click the submit button within the form and then Login.

Actual Result - fetch api is getting called multiple times, when I am filling the form, rite from the point I start typing on the form, The complete result succeeds after I complete typing the username and password and the submit button does not seem to have any affect as such.

Relevant Code About what I am taking about above :

The useform.js that you see below is the hooks that I am using.

App.js

import React, {Component} from 'react'
import './App.css'
import Header from './components/Header.js'
import Login from './components/Login.js'

class App extends Component {
  render() {                                                                                                                                                             
      return (
      <div className="container">
       <Login />
      </div>
    );
  }
}

export default App;

Login.js

import React  from "react"
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button'
import Col from 'react-bootstrap/Col'
import useForm from './useForm.js'
// Using hooks instead of a Class and constructor


const Login = () => {
    const { values, handleChange, handleSubmit } = useForm(signup)

    function signup(){
        console.log(values)
    }

    var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
        targetUrl = '...'

    fetch ( proxyUrl+targetUrl, {
            method: 'POST',
            headers: {
                'content-Type': 'application/json',
                'Accept' : 'application/json',
            },
        body: JSON.stringify(values)
    })
    .then((response) => response.json())
    .then((values) => {
        console.log('Success:', values)
    })
    .catch((error) => {
        console.error('Error:', error)
    })


    return (
<Form noValidate onSubmit={handleSubmit}>
    <Form.Row>
        <Form.Group as={Col} controlId="formGridUserName">
            <Form.Label>UserName</Form.Label>
            <Form.Control
                autoFocus
                name={'username'}
                value={values.username}
                type='username'
                placeholder="username"
                onChange={handleChange}
            />
        </Form.Group>

        <Form.Group as={Col} controlId="formGridFirstName">
            <Form.Label>First Name</Form.Label>
            <Form.Control
            autoFocus
            name={'firstname'}
            value={values.firstname}
            type='first name'
            placeholder="First name"
            onChange={handleChange}
            />
        </Form.Group>

        <Form.Group as={Col} controlId="formGridSecondName">
            <Form.Label>Last Name</Form.Label>
            <Form.Control
            autoFocus
            name={'lastname'}
            value={values.lastname}
            type='last name'
            placeholder="Last name"
            onChange={handleChange}
            />
        </Form.Group>
    </Form.Row>

    <Form.Group controlId="formBasicEmail">
        <Form.Label>Email address</Form.Label>
        <Form.Control
        autoFocus
        type="email"
        name={'email'}
        value={values.email}
        onChange={handleChange}
        placeholder="Enter email"
        />
        <Form.Text className="text-muted">
            We'll never share your email with anyone else.
        </Form.Text>
  </Form.Group>

  <Form.Group controlId="formBasicPassword">
    <Form.Label>Password</Form.Label>
    <Form.Control
        autoFocus
        type="password"
        name={'password'}
        value={values.password}
        onChange={handleChange}
        placeholder="Password" />
    </Form.Group>
        <Form.Group controlId="formBasicCheckbox">
            <Form.Check type="checkbox" label="Check me out" />
    </Form.Group>

    <Button
        variant="primary"
        type="submit"
        value="Submit"
        >
        Login
    </Button>

</Form>
  );
}

export default Login

How do I run the react app, is as simple as npm start from within the src folder, my folder structure if you are curious about some particular file, that you would want to look at

planner-app/
├── README.md
├── node_modules
├── package-lock.json
├── package.json
├── public
└── src

planner-app/src
├── App.css
├── App.js
├── components
│   ├── Header.js
│   ├── Login.css
│   ├── Login.js
│   ├── MainComponent.js
│   └── useForm.js
├── index.css
├── index.js
├── logo.svg
├── serviceWorker.js
└── setupTests.js

2 Answers 2

1

You should place your login/fetch logic only after you've submitted the form.

In this case, put your fetch logic in handleSubmit. That way, it is only called once the form submits (onSubmit).

Sign up to request clarification or add additional context in comments.

Comments

0

So a react component will run all of the code before the return statement every time the component rerenders, when you are filling in the form, the component is rerendering and therefore recalling the fetch api. To stop this, put the api code within a function that is only called when you submit the form.

const submitForm = () => {
// call api here

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.