I am writing a chat app in react and rest-api in php. However I am getting a this.state.messages is not a function error. How can I fix this. I am still new at react and php, so thank you for your help.
This is how I get the data from rest-api and here is my code for rest-api
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
try {
$query = $readDB->prepare('select id, username, text from tblmessages');
$query->execute();
$rowCount = $query->rowCount();
$messageArray = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$message = new Message($row['id'], $row['username'], $row['text']);
$messageArray[] = $message->returnMessageAsArray();
}
$returnData = array();
$returnData['rows_returned'] = $rowCount;
$returnData['messages'] = $messageArray;
$response = new Response();
$response->setSuccess(true);
$response->setHttpStatusCode(200);
$response->toCache(true);
$response->setData($returnData);
$response->send();
exit();
}
// ...
also here is the code for react
class MessagePanel extends Component {
state = {
messages: [],
}
componentDidMount = () => {
axios.get('http://localhost:8888/restapi/messages')
.then(response => {
this.setState({messages: response.data});
console.log(this.state.messages)
})
}
sendMessage = (mes) => {
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
const data = {
username: this.props.username,
text: mes
};
axios.post('http://localhost:8888/restapi/messages', data, {
headers: headers
})
.then(response => {
console.log(response)
})
};
render() {
return (
<div className="MessagePanel">
<Layout/>
<SidePanel users={this.state.usernames}/>
<DisplayMessages messages={this.state.messages} username={this.props.username}/>
<MessageBox sendMessage={this.sendMessage} username={this.props.username}/>
</div>
);
}
}
render()
{
return (
<div className="DisplayMessage">
<div className='message-container'>
{this.props.messages.map(message => {
return (
<Message key={message.id} text={message.text} username={message.username}/>
)
})}
</div>
</div>
);
}
}
export default DisplayMessages;
I can see that the response from the backend is more nested, so try to replace
this.setState({messages: response.data});
with
this.setState({messages: response.data.data[0].messages})