Wednesday, May 4, 2022

Fetching JSON data from REST APIs



data.json----------------------------------

[
    {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati exc.
    },
    {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor.

App.js



import {useEffect, useState } from 'react';
const App =() =>{
const [dataList, setDataList] = useState([]);
useEffect(()=>{
    fetch('http://localhost:3000/data.json')
    .then(response => response.json())
    .then(data => setDataList(data));
},[]);  
    return(    
 <div>    
{dataList && dataList.map((team)=>{
return (
<>
<div key={team.id}>  
<p>{team.id}</p>
<p>{team.title}</p>
</div>
  </>
)})}
    </div>  
 )
}
export default App;




Saturday, August 21, 2021

Basics of Form Handling Class Component

Class Form


 import React, { Component } from 'react';

import ReactDOM from 'react-dom';
 
export default class Welcome extends Component{
  constructor(props){
    super(props);
    this.state = {
      username:'',
      address:'',
      topic:''
    }
  }
  handleusername=(e=>{
this.setState({
  username:e.target.value
})
  }

handleaddress=(e=>{
this.setState({
address:e.target.value
})
}

handletopic=(e=>{
  this.setState({
    topic:e.target.value
  })
    }

    handleSubmit=(e)=>{
      alert(`${this.state.username} ${this.state.address} ${this.state.topic}`);
     e.preventDefault()
     console.warn(this.state.username)
    }

render(){
  return(
    <>
    <form onSubmit={this.handleSubmit}>
      <div>
      <label>User name</label>
      <input value={this.state.username} type="text" onChange={this.handleusername}/>
      </div>
      
      <div>
      <label>Address</label>
      <input value={this.state.address} type="text" onChange={this.handleaddress}/>
      </div>

      <div>
      <label>Topic</label>
 
 <select value={this.state.value} onChange={this.handletopic}> 
   <option value="Html">Html</option>
   <option value="CSS">CSS</option>
   <option value="Angulr">Angular</option>
 </select>
 
       </div>

<button type="submit">Submit</button>
    </form>
     </>
  )
}
}

ReactDOM.render( <Welcome/>,
document.getElementById('root')
);



Sunday, May 30, 2021

React JS Basic User Form master

 import React, { Component } from 'react'


class Form extends Component {
    constructor(props) {
        super(props)

        this.state = {
            firstName: "",
            lastName: "",
            password: "",
            gender: "",


        }
        this.handleSubmit=this.handleSubmit.bind(this)
    }

    firsthandler = (event=> {
        this.setState({
            firstName: event.target.value
        })
    }
    lasthandler = (event=> {
        this.setState({
            lastName: event.target.value
        })
    }
    passwordhandler = (event=> {
        this.setState({
            password: event.target.value
        })
    }

    genderhandler = (event=> {
        this.setState({
            gender: event.target.value
        })
    }

    handleSubmit = (event=> {
        alert(`${this.state.firstName} ${this.state.lastName}  Registered Successfully !!!!`)
        console.log(this.state);
        this.setState({
            firstName: "",
            lastName: "",
            password: '',
            gender: "",
        })
     event.preventDefault()
        
    }

    render() {
        return (
            <div>

                <form onSubmit={this.handleSubmit}>
                    <h1>User Registration</h1>
                    <label>FirstName :</label> <input type="text" value={this.state.firstName} onChange={this.firsthandler} placeholder="FirstName..." /><br />
                    <label>LastName :</label> <input type="text" value={this.state.lastName} onChange={this.lasthandler} placeholder="LastName..." /><br />
                    <label>Password :</label> <input type="password" value={this.state.password} onChange={this.passwordhandler} placeholder="Password..." /><br />
                    <label>Gender :</label><select onChange={this.genderhandler} defaultValue="Select Gender">
                        <option defaultValue>Select Gender</option>
                        <option value="male">Male</option>
                        <option value="female">Female</option>
                    </select><br />
                    <input type="submit" value="Submit" />
                </form>

            </div>
            
        )
    }
}

export default Form

React (function) Fetch Data From An API With React Hooks | AJAX and APIs

 


import React, { useState, useEffect } from "react";

const Planets = () => {
  const [hasError, setErrors= useState(false);
  const [planets, setPlanets= useState({});

  useEffect(() => {
    async function fetchData() {
      const res = await fetch("https://jsonplaceholder.typicode.com/posts");
      res
        .json()
        .then(res => setPlanets(res))
        .catch(err => setErrors(err));
    }

    fetchData();
  });

  return (
    <>
     {JSON.stringify(planets)}
      <hr/>
      <span>Has error: {JSON.stringify(hasError)}</span>
    </>
  )
}
export default Planets;

React (Class ) Fetch Data From An API With React Hooks | AJAX and APIs

 


import React, { Component } from "react";

export default class Planets extends Component {
  state = {
    hasErrors: false,
    planets: {}
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts"
      .then(res => res.json())
      .then(res => this.setState({ planets: res }))
      .catch(() => this.setState({ hasErrors: true }));
  }

  render() {
    return <div>{JSON.stringify(this.state.planets)}</div>;
  }
}

React js Call API(Fetch API Data)

 import React, { Component } from 'react';

import './App.css';

class App extends Component{
  constructor(){
    super();
    this.state={
      users:null
    }}
    componentDidMount()
    {
      fetch('https://reqres.in/api/users').then((resp)=>{
        resp.json().then((result)=>{
       console.warn(result.data)
       this.setState({users:result.data})
        });
      })
   } 
 
render(){
  return(
    <div>
      <h1>Fetch API Data</h1>
    
    {
      this.state.users ?
      this.state.users.map((item,i=>
     <div>{i} --- {item.first_name} --- {item.last_name} --- {item.email}</div>
      )
      :
      null
    }
   
    </div>

  )}
}




export default App;

Important things in ReactJs - Keys - Fragments - List

 import React from 'react';

import './App.css';

const Listdata = [
  {
  name:"Ujjwal Tripathi"
},
{
  name:"Pushpendra Tripathi"
},
{
  name:"Tripti Tripathi"
},
]

const List = () =>{
return Listdata.map((val,index)=>{
  return<li key={index}>{val.name}</li>
});
}
 
const Biodata = () =>{
  return(
    <>
      <p>Name - Jonson</p>
      <p>Address - USA</p>
    </>
  )
}
function App() {
return (
<div>
  <List/>
<Biodata/>
</div>    
  );}
export default App;

Fetching JSON data from REST APIs

data.json---------------------------------- [     {     "userId" : 1 ,     "id" : 1 ,     "title" : "sunt...