React JS + PHP help

Asked

Viewed 2,480 times

0

Well I’m having difficulty and I haven’t found a solution yet, wanted to develop a crud using Reactjs + PHP + Mysql; I made a php file that returns a JSON object so I can access it from React.

<?php
    //Header
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    //
    include '../conf/database.php';
    include '../objects/carro.php';
    //
    $database = new Database();
    $db = $database->getConnection();
    //
    $carro = new Carro($db);
    //
    $stmt = $carro->read();
    $num = $stmt->rowCount();
    //
    if($num>0){
        $carros_arr=array();
        $carros_arr["records"]=array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);
            $carros_arr["records"][$id] = array(
                "id" => $id,
                "nome" => $nome,
                "descricao" => html_entity_decode($descricao),
                "marca" => $marca,
                "valor" => $valor
            );
        }
        http_response_code(200);
        echo json_encode($carros_arr);
    }else {
        http_response_code(404);
        echo json_encode(
            array("message" => "No products found.")
        );
    }
?>

And the React file:

import React, {Component} from 'react';
import './styles.css';
import axios from 'axios';

export default class Main extends Component{
    state = {
        carros : [],
        isLoading : true
    }

    componentDidMount(){
        this.loadCars();
    }

     loadCars(){
        const url = "http://localhost/apihunt/carro/read.php";

        //METODO 1
        /*axios(url)
        .then(response => response.data)
        .then(data => {
            this.setState({
                carro : data,
                isLoading : false
            });    
        });*/

        //METODO 2
        /*const response =  axios(url);
        const {records} = response.data;
        this.setState({
            carro : records
        })*/

        //METODO 3
        fetch("http://localhost/apihunt/carro/read.php")
        .then((response) => response.json())
        .then((responseJson) => (
            this.setState({
                carros : responseJson
            })
        ));
        console.log(this.state.carros);
    }

    render(){
        return(
            <div className="list-item">

            </div>
        );
    }
}


None of the methods are working, and I also tried to use async-await;

Any suggestions or a CRUD using React, PHP and mysql?

  • If you put http://localhost/apihunt/carro/read.php directly in the browser url for JSON?

  • yes, the php code is running perfectly , and Next in js is assigning the array to the state, the problem is just when I use the map in the array says "Object.map is not Function"

  • Answer : https://stackoverflow.com/questions/56114358/react-js-phpmysql-records-map-is-not-a-function/56115646#56115646 The problem was in php.

2 answers

0

The console.log(this.state.carros); shortly after the setState will not work because setState is asynchronous. Place the console.log inside the render(): should appear s output a couple times on the console being the last one after the state has actually changed.

If the PHP call is OK what is being returned is not an array but a json object in the format:

{"Records":{"1":{"id":"1","name":"car 1","Description":"Description 1","Mark":"Mark 1","Value":"1.00"},"2""}}}

View generation using php here: http://sandbox.onlinephpfunctions.com/code/9293cf990a2bc7a23b37a5faf9ce28606bfde39b

An object must be traversed with the methods of Object :

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const { records } = {
    records: {
      "1": {
        id: "1",
        nome: "carro 1",
        descricao: "descricao 1",
        marca: "marca 1",
        valor: "1.00"
      },
      "2": {
        id: "2",
        nome: "carro 2",
        descricao: "descricao 2",
        marca: "marca 2",
        valor: "2.00"
      },
      "3": {
        id: "3",
        nome: "carro 3",
        descricao: "descricao 3",
        marca: "marca 3",
        valor: "3.00"
      }
    }
  };
  const carros = Object.values(records).map(c => (
    <li>
      {c.id} || {c.nome} || {c.descricao} || {c.marca} || {c.valor}
    </li>
  ));

  return (
    <div className="App">
      <h1>Carros</h1>
      <ul>{carros}</ul>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

See the React code working here: https://codesandbox.io/s/floral-river-o7r7k

Remembering that the mapping of the object that comes from PHP and is set in state should be done in render and not soon after calling setState.

0

The function map only works in Arrays, to make sure the return of the api is within a Array use the following code

//METODO 3
fetch("http://localhost/apihunt/carro/read.php")
 .then((response) => response.json())
  .then((responseJson) => (
    this.setState({
      carros : [responseJson]//coloque dentro de um array
    })
));
  • But then if it is already an array will give problem. Can do: cars: Array.isArray(responseJson) ? responseJson : [responseJson]

  • Returns a string containing the JSON representation of the supplied value. when it does json_encode returns a string, when the setState function is called returns a new state.

  • In this case cars would be an array containing a single element that would be the string representing the json. Which is not what OP wants.

  • Exactly as the return of this json will see something like {{...}} the map will not work, the return of this json should something like this [{...},{...},...], as it is not so setState({cars:[responseJson]}) will solve

  • No, the return is something like this: {"Records"{"1": {"id":"1","name":"car 1"...},{"2":{...}...}. Placing this between square brackets will create an array with a single element that is the same object it received from the server. See my response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.