Records from the table is not displayed in the front end

Viewed 140

I am new to Laravel and ReactJS, am trying to achieve a CRUD operation, I am trying to display the 4 rows from the table but am able to insert records into the table but not able to read. Any help is appreciated. Laravel Framework 7.10.3 PHP 7.4.5 Composer version 1.10.6 Mysql And following is the code details

DisplayProduct.js

import React, {Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router';
import TableRow from './TableRow';
import MyGlobleSetting from './MyGlobleSetting';

class DisplayProduct extends Component {
  constructor(props) {
       super(props);
       this.state = {value: '', products: ''};
     }
     componentDidMount(){
       axios.get(MyGlobleSetting.url + '/api/products')
       .then(response => {
         this.setState({ products: response.data });
        console.log(response.data);
        console.log(this.state.products);
       })
       .catch(function (error) {
         console.log(error);
       })
     }

     tabRow(){
       if(this.state.products instanceof Array){
         return this.state.products.map(function(object, i){
            return <TableRow obj={object} key={i} />;
         })
       }
     }

  render(){
    return (
      <div>
        <h1>Products</h1>


        <div className="row">
          <div className="col-md-10"></div>
          <div className="col-md-2">
            <Link to="/add-item">Create Product</Link>
          </div>
        </div><br />


        <table className="table table-hover">
            <thead>
            <tr>
                <td>ID</td>
                <td>Product Title</td>
                <td>Product Body</td>
                <td width="200px">Actions</td>
            </tr>
            </thead>
            <tbody>
          {this.tabRow()}
            </tbody>
        </table>
    </div>
    )
  }
}
export default DisplayProduct;

TableRow.js

import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router';
import axios from 'axios';
import MyGlobleSetting from './MyGlobleSetting';


class TableRow extends Component {
 constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(event) {
    event.preventDefault();
    let uri = MyGlobleSetting.url + `/api/products/${this.props.obj.id}`;
    axios.delete(uri);
      browserHistory.push('/display-item');
  }
  render() {
    return (
        <tr>
          <td>
            {this.props.obj.id}
          </td>
          <td>
            {this.props.obj.title}
          </td>
          <td>
            {this.props.obj.body}
          </td>
          <td>
          <form onSubmit={this.handleSubmit}>
            <Link to={"edit/"+this.props.obj.id} className="btn btn-primary">Edit</Link>
           <input type="submit" value="Delete" className="btn btn-danger"/>
         </form>
          </td>
        </tr>
    );
  }
}


export default TableRow;

welcome.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel ReactJS CRUD Example</title>
         <link href="{{mix('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id='crud-app'></div>
       <script src="{{mix('js/app.js')}}" ></script>
    </body>
</html>

ProductController.php

<?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;


class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::all();
        return response()->json($products);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $product = new Product([
          'title' => $request->get('title'),
          'body' => $request->get('body')
        ]);
        $product->save();


        return response()->json('Product Added Successfully.');
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = Product::find($id);
        return response()->json($product);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $product = Product::find($id);
        $product->title = $request->get('title');
        $product->body = $request->get('body');
        $product->save();


        return response()->json('Product Updated Successfully.');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
      $product = Product::find($id);
      $product->delete();


      return response()->json('Product Deleted Successfully.');
    }
}
?>

Master.js

import React, {Component} from 'react';
import { Router, Route, Link } from 'react-router';


class Master extends Component {
  render(){
    return (
      <div className="container">
        <nav className="navbar navbar-default">
          <div className="container-fluid">
            <div className="navbar-header">
              <a className="navbar-brand" href="/">Products Maintenance</a>
            </div>
            <ul className="nav navbar-nav">
              <li><Link to="/">Home</Link></li>
              <li><Link to="add-item">Create Product</Link></li>
              <li><Link to="display-item">Products</Link></li>
            </ul>
          </div>
      </nav>
          <div>
              {this.props.children}
          </div>
      </div>
    )
  }
}
export default Master

app.js

require('./bootstrap');
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import Master from './components/Master';
import CreateProduct from './components/CreateProduct';
import DisplayProduct from './components/DisplayProduct';
import UpdateProduct from './components/UpdateProduct';


render(
  <Router history={browserHistory}>
      <Route path="/" component={Master} >
        <Route path="/add-item" component={CreateProduct} />
        <Route path="/display-item" component={ DisplayProduct} />
        <Route path="/edit/:id" component={UpdateProduct} />
      </Route>
    </Router>,
        document.getElementById('crud-app'));
1 Answers

UPDATED CODE

In your main js file, lets say App.js component you will have a router set already for this link

<li><Link to="display-item">Products</Link></li>

The router will looks something like this

<Route path="/display-item" exact component={DisplayProduct} />

Include your DisplayProduct.js component and this way when you click products link you will be able to show whole component.

I have used this way and it's working see if it helps you too.

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

class App extends Component {
render () {
    return (
        <BrowserRouter>
            <div>
                <Header />
                <Switch>
                    <Route path="/student" exact component={Student} />
                    <Route path="/classes" exact component={Classes} />
                </Switch>
            </div>
        </BrowserRouter>
    )
}
}

if (document.getElementById('app')) {
   ReactDOM.render(<App />, document.getElementById('app'));
}

I see in your code that you don't have a <div> for rendering in your render method, you need to have it atleast one. Also I think you have included document.getElement.... inside your render method, that may be causing the problem.

Related