I was following the documentation on strapi and react but i get this console error:
this.state.restaurants.map is not a function
If i console log the data it gives me this response
But trying to display them on frontend its not working
This is with the Fetch method
import React from "react";
class App extends React.Component {
state = {
restaurants: [],
error: null,
};
componentDidMount = async () => {
const parseJSON = (resp) => (resp.json ? resp.json() : resp);
const checkStatus = (resp) => {
if (resp.status >= 200 && resp.status < 300) {
return resp;
}
return parseJSON(resp).then((resp) => {
throw resp;
});
};
const headers = {
"Content-Type": "application/json",
};
try {
const restaurants = await fetch("http://localhost:1337/api/restaurants", {
method: "GET",
headers: headers,
})
.then(checkStatus)
.then(parseJSON);
this.setState({ restaurants });
} catch (error) {
this.setState({ error });
}
};
render() {
const { error, restaurant } = this.state;
if (error) {
return <div>An error occured: {error.message}</div>;
}
return (
<div className="App">
<ul>
{this.state.restaurants.map((restaurant) => (
<li key={restaurant.id}>{restaurant.name}</li>
))}
</ul>
</div>
);
}
}
export default App;
This is Axios method
import React from 'react';
import axios from 'axios';
class App extends React.Component {
// State of your application
state = {
restaurants: [],
error: null,
};
// Fetch your restaurants immediately after the component is mounted
componentDidMount = async () => {
try {
const response = await axios.get('http://localhost:1337/api/restaurants');
this.setState({ restaurants: response.data });
} catch (error) {
this.setState({ error });
}
};
render() {
const { error, restaurant } = this.state;
// Print errors if any
if (error) {
return <div>An error occured: {error.message}</div>;
}
return (
<div className="App">
<ul>
{this.state.restaurants.map(restaurant => (
<li key={restaurant.id}>{restaurant.name}</li>
))}
</ul>
</div>
);
}
}
export default App;
My strapi roles on Public have the checked mark to find and findOne the same as on this documentation.
You get restaurants from response.data
but the response have an object
with data: { data: ... }
.
Solution:
this.setState({ restaurants: response.data.data });