I want to create a frontend using react for my PHP rest API. I try to read the data from the rest api but I can't manage to fetch it properly. I tested all the requests in Postman and they work fine, but I have no clue why they don't work in react.
I tried to do it with axios/fetch/get but I always get the same error TypeError: items.map is not a function. Should I rewrite my rest API? My API is returning a JSON and I don't know if I need to decode it in react?
My php code:
public function read() {
// Create query
$query = 'SELECT * FROM ' . $this->table ;
// Prepare statement
$stmt = $this->conn->prepare($query);
// Execute query
$stmt->execute();
return $stmt;
}
API readUM.php
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Post2.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate post object
$post = new Post2($db);
// Blog post query
$result = $post->read();
// Get row count
$num = $result->rowCount();
// Check if any posts
if ($num > 0) {
// Post array
$posts_arr = array();
$posts_arr['data'] = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$post_item = array(
'id' => $id,
'name' => $name,
'location' => $location,
'type' => $type,
'logo' => $logo
);
// Push to "data"
//array_push($posts_arr, $post_item);
array_push($posts_arr['data'], $post_item);
}
// Turn to JSON & output
echo json_encode($posts_arr);
} else {
// No Posts
echo json_encode(
array('message' => 'No Posts Found')
);
}
Result in postman:
{
"data": [
{
"id": "1",
"name": "Test",
"location": "Cluj",
"type": "Test",
"logo": null
}
]
}
My react code:
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false,
}
}
componentDidMount() {
fetch('http://localhost/fak/api/post/readUM.php')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
})
});
}
render() {
let {isLoaded, items} = this.state;
if (!isLoaded) {
return <div>Loading...</div>
} else {
return (
<div className="App ">
<ul>
{items.map(item => (
<li key={item.id}>
Name: {item.name} | Location:{item.location}
</li>
))};
</ul>
</div>
);
}
}
}
Console.log(json):
Object
data: Array(1)
0: {id: "1", name: "Test", location: "Cluj", type: "Test", logo: null}
length: 1
__proto__: Array(0)
__proto__: Object