Hi coders!
Has anyone encountered the error from this lecture? If so, can someone explain the solution to it please?
I can’t get passed by it as it keeps on showing this:
This error shows up, once I click on the update button.
Here’s the code I have for the handleUpdate method:
handleUpdate = async (post) => {
post.title = "UPDATED";
await axios.put(apiEndPoint + "/" + post.id, post);
const posts = [...this.state.posts];
const index = posts.indexOf(post);
posts[index] = { ...post };
this.setState({ posts });
};
And here’s the code I have for the app.js just incase someone asks for it:
import React, { Component } from "react";
import axios from "axios";
import "./App.css";
const apiEndPoint = "https://jsonplaceholder.typicode.com/posts";
class App extends Component {
state = {
posts: []
};
async componentDidMount() {
const { data: posts } = await axios.get(apiEndPoint);
this.setState({ posts });
}
handleAdd = async () => {
const obj = {
title: "a",
body: "b"
};
const { data: post } = await axios.post(apiEndPoint, obj);
console.log(post);
const posts = [post, ...this.state.posts];
this.setState({ posts });
};
handleUpdate = async (post) => {
post.title = "UPDATED";
await axios.put(apiEndPoint + "/" + post.id, post);
const posts = [...this.state.posts];
const index = posts.indexOf(post);
posts[index] = { ...post };
this.setState({ posts });
};
handleDelete = () => {
console.log("Delete has been clicked");
};
render() {
return (
<React.Fragment>
<button className="btn btn-primary mb-2" onClick={this.handleAdd}>
Add
</button>
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{this.state.posts.map((post) => (
<tr key={post.id}>
<td>{post.title}</td>
<td>
<button
className="btn btn-info btn-sm"
onClick={this.handleUpdate}
>
Update
</button>
</td>
<td>
<button
className="btn btn-danger btn-sm"
onClick={this.handleDelete}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</React.Fragment>
);
}
}
export default App;
Thanks in advance!