ReactJS REST CALL Example : Populate a list Search box enter key press.


This demo shows,
1. Updating a list within the react component
2. Updating a list in child react component by passing 'state' as 'props'
3. Updating simple 'props'
4. All the updates are on 'Enter Key' press on an input field.




//demo.js

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import ListSubheader from "@material-ui/core/ListSubheader";
import TextField from "@material-ui/core/TextField";

const styles = theme => ({
  root: {
    width: "100%",
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
    position: "relative",
    overflow: "auto",
    maxHeight: 300
  },
  listSection: {
    backgroundColor: "inherit"
  },
  ul: {
    backgroundColor: "inherit",
    padding: 0
  }
});

class RestTest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchkey: "Jurassic",
      movies: [],
      keye: "yyy",
      mo: [
        {
          Title: "Jurassic World",
          Type: "movie",
          Year: "2015",
          imdbID: "tt0369610"
        },
        {
          Title: "Jurassic World11",
          Type: "movie",
          Year: "2015",
          imdbID: "tt03696101"
        }
      ]
    };
  }

  handleChange = searchkey => event => {
    if (event.key === "Enter") { 
      event.currentTarget.style.backgroundColor = "#cfffff";
      this.setState({
        [searchkey]: event.target.value
      }); 
      console.log("enter press here! "); 
      this.callRest(event.target.value);
      // console.log(" movies   here! ", this.state.movies);
    } 
  };

  // componentDidMount() {
  callRest(searchkey) {
    console.log(" searchkey   here! ", searchkey);
    const axios = require("axios");
    // Is there a React-y way to avoid rebinding `this`? fat arrow?
    const th = this;
    const url = `https://www.omdbapi.com/?s=${searchkey}&apikey=1149d830`;
    axios
      .get(url)
      .then(response => {
        // handle success
        this.setState({
          movies: response.data.Search,
          keye: "hihi"
        });
        console.log("res...", this.state.movies);
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      })
      .then(function() {
        // always executed
        return false
      });
  }

  componentWillUnmount() {
    // this.serverRequest.abort();
  }
  render() {
    const { classes } = this.props; 
    return (
      <div>
        <TextField
          id="searchkey"
          label="search keyword"
          className={classes.textField}
          defaultValue="Jurassic"
          onKeyPress={this.handleChange("searchkey")}
          margin="normal"
        />
        {this.state.mo.map(movie => (
          <p key={movie.imdbID}>Title : {movie.Title} </p>
        ))}

        <PinnedSubheaderList
          classes={this.props.classes}
          keye={this.state.keye}
          movies={this.state.movies}
          {...this.state}
        />
      </div>
    );
  }
}

function PinnedSubheaderList(props) {
  const { classes } = props;

  if (props.movies){
  return (
    <div>
      <h1>{props.keye}</h1>

      { props.movies.map(movie => (
        <p key={movie.imdbID}>Title : {movie.Title}</p>
      ))}
    </div>
  );
  }else { return (<h1>{`No data found`}</h1>)}
}

export default withStyles(styles)(RestTest);




//index.js

import React from 'react';
import { render } from 'react-dom';
import Demo from './demo';

const rootElement = document.querySelector('#root');
if (rootElement) {
  render(<Demo />, rootElement);
}
      
      
//index.html

<body>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
  <div id="root"></div>
</body>
      

Comments