I’m reworking a program I worked on last week to take data from an API and need to update the reviews by using PUT, however, the form section is giving my issues. When I click on the Submit button the user’s review is supposed to render onto the app, but when Submit is clicked nothing happens.
So far the code I have uses PUT but I have POST as well. I’m not sure which would be better to use, what should I be using to add data to the API?
Here is the code I have so far for the App component:
App Component:
import './App.css';
import React, { useState, useEffect } from 'react';
import ToDoForm from './ToDoForm';
import ToDoList from './ToDoList';
import { fetchAPI } from './utils';
const URL = 'https://api-server-xki8.onrender.com/todos';
function App() {
const [todos, setStoreToDos] = useState([]);
useEffect(() => {
let options = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
};
async function fetchData() {
try {
const todosData = await fetchAPI(URL, options);
todosData.sort((a, b) => (a.id < b.id) ? 1 : -1);
setStoreToDos(todosData);
} catch (error) {
console.error('Error fetching data!', error.message);
setError('Error setting data. Please try again later.');
}
}
fetchData();
}, []);
const addToDos = async (val) => {
const newToDoItems = {
text: val,
isCompleted: false,
};
let options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newToDoItems),
};
try {
const newTodo = await fetchAPI(URL, options);
const newToDos = [...todos, newTodo].sort((a, b) =>
(a.id < b.id) ? 1 : -1
);
setStoreToDos(newToDos);
} catch (error) {
console.error('Error:', error.message);
}
};
const completeToDo = async (id) => {
const tempToDos = [...todos];
const index = tempToDos.findIndex((todos) => todos.id === id);
tempToDos[index].isCompleted = !tempToDos[index].isCompleted;
const updatedToDo = {
text: tempToDos[index].text,
isCompleted: tempToDos[index].isCompleted
};
let options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updatedToDo)
};
try {
await fetch(`${URL}/${id}`, options);
setStoreToDos(tempToDos);
} catch (error) {
console.error('Error:', error.message);
}
};
const deleteToDos = async (id) => {
let options = {
method: 'DELETE'
};
try {
const resDelete = await fetch(`${URL}/${id}`, options);
if (!resDelete.ok) {
throw new Error('DELETE failed!');
}
const res = await fetch(URL);
const data = await res.json();
setStoreToDos(data);
} catch (error) {
console.error('Error:', error.message);
}
};
const editToDos = async (id, text) => {
try {
const temporaryToDos = [...todos];
const index = temporaryToDos.findIndex((todo) => todo.id === id);
temporaryToDos[index].text = text;
const updatedToDo = {
text,
isCompleted: temporaryToDos[index].isCompleted
};
let options = {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedToDo)
};
await fetch(`${URL}/${id}`, options);
setStoreToDos(temporaryToDos);
} catch (error) {
console.error('Error', error.message);
}
};
// console.log("App is Rendering");
return (
<>
<h2>To Do App</h2>
<h5>Add New To Do Items via the Input Field: </h5>
<ToDoForm addToDos={addToDos} />
<ToDoList
todos={todos}
completeToDo={completeToDo}
deleteToDos={deleteToDos}
editToDos={editToDos}
/>
</>
);
}
export default App;
import React, { useState} from 'react';
// import { fetchAPI } from './utils';
import StarRating from './StarRating.jsx';
function UserRating({ movieID, onUpdateReview}) {
const [user, setUser] = useState('');
const [review, setReviews] = useState('');
const [stars, setStars] = useState(0);
const handleUser = (e) => {
setUser(e.target.value);
};
const handleReview = (e) => {
setReviews(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
const addReview = ({
movieID,
user: user,
review: review,
rating: stars
}
)
onUpdateReview(addReview)
formReset();
};
const formReset = () => {
setUser('');
setReviews('');
setStars(0);
};
return (
<div className="userReview">
<form onSubmit={handleSubmit} >
<h2>Rate This Movie:</h2>
<label>
<label>
Name:
<input
type="text"
value={user}
onChange={handleUser}
required
placeholder={'Enter Name Here:'}
/>
</label>
<label>
Review:
<textarea
value={review}
onChange={handleReview}
required
placeholder={'Enter Review Here:'}
rows={8}
cols={39}
></textarea>
</label>
</label>
<StarRating disabled={false} stars={stars} set={setStars} />
<button type="submit" value="Submit">
Submit {''}
</button>
</form>
</div>
);
}
export default UserRating;
So far, I’ve tried using PUT and have a function in the UserRating component to submit data. I’ve tried different variations of the value tempMovies[index] including using tempMovies[index].user = user, tempMovies[index].user = !tempMovies[index].user. I had also tried to make a useState in UserRating that would set the values of the form into the handleSubmit function, but it causes the program to crash.