Issue
I have a friend form that has a button to add friend via ajax call (addNewFriendClick). Once added it should output the id and then using that id the same button (onClickUpdate) should allow to update by grabbing that id. After adding and clicking a second time to update the friend I get the error below in my console.
The website below should have the /id as the url ending endpoint but i am getting "[object%20Object]"
PUT https://api.remotebootcamp.dev/api/friends/[object%20Object] 404 (Not Found)
Below is my Routes
<Route path="/friends/*" element={<AddFriend></AddFriend>}>
<Route path=":personId" element={<AddFriend />}></Route>
<Route path="new" element={<AddFriend />}></Route>
</Route>
import React, { useState, useEffect } from "react";
import * as friendService from "../../services/friendService";
import toastr from "toastr";
import { useParams, useNavigate, useLocation } from "react-router-dom";
function AddFriend() {
const [userFormData, setUserFormData] = useState({
title: "",
bio: "",
summary: "",
headline: "",
slug: "",
statusId: "",
primaryImage: "",
});
// useEffect to grab url
const navigate = useNavigate();
const { state } = useLocation();
const friendId = useParams();
const [peepId, setPeepId] = useState(friendId);
console.log({ userFormData, peepId, state }, "param and navigate");
useEffect(() => {
console.log("useEffect firing");
setPeepId(friendId);
if (state) {
setUserFormData((prevState) => {
console.log(state);
return { ...prevState, ...state.payload };
});
}
}, [friendId, state]);
const onFormFieldChange = (event) => {
const target = event.target;
const value = target.value;
console.log("VALUE ->", value);
const name = target.name;
console.log("NAME ->", name);
setUserFormData((prevState) => {
console.log("updater onChange");
const updatedFormData = {
...prevState,
};
updatedFormData[name] = value;
return updatedFormData;
});
};
useEffect(() => {
console.log("useEffect firing");
setPeepId(friendId);
if (state) {
setUserFormData((prevState) => {
console.log(state);
return { ...prevState, ...state.payload };
});
}
}, [friendId, state]);
const addNewFriendClick = (event) => {
event.preventDefault();
console.log(userFormData, "inside addNewFriendClick")
console.log("on Click", { syntheticEvent: event });
friendService.addFriend(userFormData).then(onSuccessAdd).catch(onErrAdd);
};
const onSuccessAdd = (response) => {
console.log(response, "onSuccessAdd response");
// console.log(response.data.item, "onSuccessAdd response.data.item");
setNewFriendInformation(response);
console.log(response,"onSuccessAdd after setNewFriend" )
friendService.getFriendById(response).then(onSuccessGet).catch(onErrorGet);
toastr.success("Congratulations! You have successfully added a friend!");
};
const onErrAdd = (err) => {
console.log("ping err", err);
// swal("Error Registering");
toastr.error(
"Error adding a new friend. Please check if all fields are correct"
);
};
const onClickUpdate = (event) => {
console.log(userFormData, "userFormData inside click Edit");
event.preventDefault();
friendService
.updateFriend(userFormData)
.then(onSuccessUpdate)
.catch(onErrorUpdate);
};
const onSuccessUpdate = (response) => {
console.log(response);
toastr.success("Congratulations! You have successfully updated a friend!");
navigate("/friends");
};
const onErrorUpdate = (error) => {
console.log(error, "inside error update");
toastr.error(
"Error updating friend. Please check all fields are correct and that user being updated is valid"
);
};
const setNewFriendInformation = (id) => {
setUserFormData((prevState) => {
let newState = { ...prevState };
newState.id = id;
return newState;
});
};
const onSuccessGet = (response) => {
console.log(response);
navigate();
};
const onErrorGet = (error) => {
console.log(error);
console.log("inside getById error form");
};
// const updateFriend()
return (
<React.Fragment>
<h1 className="container">Add New</h1>
<hr />
<main role="main">
<div className="container col-6 mt-5 fs-2">
<div className="row">
<div className="col-md-5">
<form>
<div className="mb-3">
<label htmlFor="title" className="form-label">
Title
</label>
<input
type="text"
className="form-control form-control-lg"
id="title"
name="title"
placeholder="Please The Enter Title"
onChange={onFormFieldChange}
value={userFormData.title}
/>
</div>
<div className="mb-3">
<label htmlFor="bio" className="form-label">
Bio
</label>
<input
type="text"
className="form-control form-control-lg"
id="bio"
name="bio"
placeholder="Please Enter The Bio"
value={userFormData.bio}
onChange={onFormFieldChange}
/>
</div>
<div className="mb-3">
<label htmlFor="summary" className="form-label">
Summary
</label>
<input
type="text"
className="form-control form-control-lg"
id="summary"
name="summary"
placeholder="Please Enter The Summary"
onChange={onFormFieldChange}
value={userFormData.summary}
/>
</div>
<div className="mb-3">
<label htmlFor="headline" className="form-label">
Headline
</label>
<input
type="text"
className="form-control form-control-lg"
id="headline"
name="headline"
placeholder="Please Enter The Headline"
onChange={onFormFieldChange}
value={userFormData.headline}
/>
</div>
<div className="mb-3">
<label htmlFor="slug" className="form-label">
Slug
</label>
<input
type="text"
className="form-control form-control-lg"
id="slug"
name="slug"
placeholder="Please The Slug"
onChange={onFormFieldChange}
value={userFormData.slug}
/>
</div>
<div className="mb-3">
<label htmlFor="statusId" className="form-label">
Status Id
</label>
<select
type="select"
className="form-control"
id="statusId"
name="statusId"
placeholder="Please Enter Status ID"
onChange={onFormFieldChange}
value={userFormData.statusId}
>
<option>Default</option>
<option value="Active">Active</option>
<option value="NotSet">NotSet</option>
<option value="Deleted">Deleted</option>
<option value="Flagged">Flagged</option>
</select>
</div>
<div className="mb-3">
<label htmlFor="primaryImage" className="form-label">
Primary Image Url
</label>
<input
type="text"
className="form-control form-control-lg"
id="primaryImage"
name="primaryImage"
placeholder="Please Enter The Primary Image"
onChange={onFormFieldChange}
value={userFormData.primaryImage}
/>
</div>
{userFormData.id ? (
<button
onClick={onClickUpdate}
type="sumbit"
className="btn btn-primary"
>
Update Friend
</button>
) : (
<button
onClick={addNewFriendClick}
type="sumbit"
className="btn btn-primary"
>
Add Friend
</button>
)}
</form>
</div>
</div>
</div>
<div className="col-md-5">
<h5>Output</h5>
<pre>
<code>{JSON.stringify(userFormData, undefined, 2)}</code>
</pre>
</div>
</main>
</React.Fragment>
);
}
export default AddFriend;
import axios from "axios";
import * as helper from "./serviceHelper";
let getFriend = () => {
const config = {
method: "GET",
url: "https://api.remotebootcamp.dev/api/friends?pageIndex=0&pageSize=10",
withCredentials: true,
crossdomain: true,
headers: { "Content-Type": "application/json" },
};
return axios(config).then(helper.onGlobalSuccess);
//we use data as the param for success handler
};
let addFriend = (payload) => {
const config = {
method: "POST",
url: "https://api.remotebootcamp.dev/api/friends",
data: payload,
withCredentials: true,
crossdomain: true,
headers: { "Content-Type": "application/json" },
};
return axios(config).then(response => {
console.log(response, "inside service addfriend return")
return response.data.item;
});
}
let updateFriend = (id, payload) => {
console.log(id, payload, "from updateFriendservice");
const config = {
method: "PUT",
data: (id, payload),
url: `https://api.remotebootcamp.dev/api/friends/${id}`,
withCredentials: true,
crossdomain: true,
headers: { "Content-Type": "application/json" },
};
return axios(config);
};
let deleteFriend = (id) => {
console.log(id);
const config = {
method: "DELETE",
// data: id,
url: `https://api.remotebootcamp.dev/api/friends/${id}`,
withCredentials: true,
crossdomain: true,
headers: { "Content-Type": "application/json" },
};
return axios(config);
};
let getFriendById = (id, payload) =>{
console.log(id, payload, "inside getFriend friedService")
const config = {
method: "PUT",
data: (id, payload),
url: `https://api.remotebootcamp.dev/api/friends/${id}`,
withCredentials: true,
crossdomain: true,
headers: { "Content-Type": "application/json" },
}
return axios(config);
}
export { getFriend, addFriend, deleteFriend, updateFriend, getFriendById };
Solution
Maybe you should get friendId as following
const { personId: friendId } = useParams();
Also you need to send two prams to friendService.updateFriend()
but sent only one param.
Answered By - First Arachne Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.