0

React JS

I'm new to react js

In my api there is username and password. If the user login, have to validate from my json value

 handleSubmit(e) {

fetch('https://randomuser.me/api?results=1')
  .then((response) => {
    return response.json()
      .then((json) => {
        if (response.ok) {
          return Promise.resolve(json)
        }
        return Promise.reject(json)
      })        
  })

alert(json) not working to check the result. How can i fetch the username and password in the response?

And how to take this next page if the user was logged in successfully ?

My full Code

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';

const ReactCSSTG = CSSTransitionGroup;

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isVisible: true
    }
    // Bindings
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleRemount = this.handleRemount.bind(this);
  }


  handleSubmit(e) {
    alert("dsa");

    fetch('https://randomuser.me/api?results=1')
      .then((response) => {
        return response.json()
          .then((json) => {
            if (response.ok) {
              return Promise.resolve(json)
            }
            return Promise.reject(json)
          })            
      })


  }
  handleRemount(e) {
    this.setState({
      isVisible: true
    }, function () {
      console.log(this.state.isVisible)
    });
    e.preventDefault();
  }


  render() {

    // const for React CSS transition declaration
    let component = this.state.isVisible ? <Modal onSubmit={this.handleSubmit} key='modal' /> : <ModalBack onClick={this.handleRemount} key='bringitback' />;

    return <ReactCSSTG transitionName="animation" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={300}>
      {component}
    </ReactCSSTG>
  }
}

// Modal
class Modal extends React.Component {

  render() {

    return <div className='Modal'>
      <Logo />
      <form onSubmit={this.props.onSubmit}>
        <Input type='text' name='username' placeholder='username' />
        <Input type='password' name='password' placeholder='password' />
        <button> Sign In</button>
      </form>

      <a href='#'>Lost your password ?</a>
    </div>
  }
}

// Generic input field
class Input extends React.Component {
  render() {
    return <div className='Input'>
      <input type={this.props.type} name={this.props.name} placeholder={this.props.placeholder} required />
      <label htmlFor={this.props.name}></label>
    </div>
  }

}

// Fake logo
class Logo extends React.Component {
  render() {
    return <div className="logo">
      <i><img src={logo} className="App-logo" alt="logo" /></i>
      <span> Test </span>
    </div>
  }
}

// Button to brind the modal back
class ModalBack extends React.Component {
  render() {
    return (
      <button className="bringitback" onClick={this.props.onClick} key={this.props.className}>Back to login page!</button>
    );

  }
}


export default App;

Thanks in Advance!

4
  • where's alert(json) ? Commented Sep 6, 2018 at 7:01
  • @BhojendraRauniyar Where ever i keep alert its not working. I don't know where to call the alert. :( Commented Sep 6, 2018 at 7:03
  • then your question becomes unclear to us. Commented Sep 6, 2018 at 7:04
  • I need to get the data while fetching.. That's all i need now @BhojendraRauniyar Commented Sep 6, 2018 at 7:05

3 Answers 3

1

If you just want to catch data for now this will do the trick

  fetch('https://randomuser.me/api?results=1')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });
Sign up to request clarification or add additional context in comments.

2 Comments

It's quite good.. How to take username and password from the json data? @LazarNikolic ?
Use this instead of JSON.stringify inside console.log myJson.results[0].login.username, myJson.results[0].login.password and you will get username and password. If you liked my answer, can you please upvote it or mark it as resolved.
0
fetch('https://randomuser.me/api?results=1')
.then((response) => {
   // check for status code from service if success
   // set response in state such as login success
   this.route.navigate(['/']);
  })
.catch(error =>{
   console.log(error);
});    

})

Taking user to next page. Use react router for achieving this.

Step 1: Wrap your <App /> inside <BrowserRouter />

Now validate response if username/password are correct using service call.

Then this.route.navigate(['/']);

This will navigate user to home page of app after successful login.

Comments

0

Heres What I did, keep in mind I set up my backend with express/node. I used Axios to fetch from my api.

onSubmit = (e) => {
    e.preventDefault();
    axios.get('API_PATH')
    .then(res => {
      const user = res.data[0].username;
      const password = res.data[0].password;
      const username = this.state.username;
      const passwordEntered = this.state.password;
      if(username === '' && passwordEntered === ''){
        document.getElementById('status').innerHTML = '<p>Please Enter A Valid Username and Password</p>';
      }else if(user === username && passwordEntered === password){
        document.getElementById('status').innerHTML = '';
        console.log(user, password)
      }else{
          document.getElementById('status').innerHTML = '<p>Please Enter A Valid Username and Password</p>';
      }
    })
    .catch(error => {
      console.log(error);
    });

  }

Here is the form I used.

<Form
          >
              <Form.Row>
              <Form.Group as={Col}>
              <Form.Label>Username</Form.Label>
                <Form.Control
                type="text"
                name="username"
                id="username"
                value={this.state.value}
                onChange={this.handleChange}
                >
                </Form.Control>
              </Form.Group>
              <Form.Group as={Col}>
                <Form.Label>Password</Form.Label>
                <Form.Control
                type="text"
                id="password"
                name="password"
                value={this.state.value}
                onChange={this.handleChange}
                />
              </Form.Group>
              </Form.Row>
              <Button className="btn btn-sm btn-light" onClick={this.onSubmit}>
                <i style={redColor} className="fas fa-sign-in-alt"></i> Login
              </Button>
        </Form>

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.