Unexpected token 2 in JSON at position 0? - reactjs

express
this is the error " at JSON.parse ()
at createStrictSyntaxError (E:\programming_hero\phone-store-server\node_modules\body-parser\lib\types\json.js:160:10)
at parse (E:\programming_hero\phone-store-server\node_modules\body-parser\lib\types\json.js:83:15)
at E:\programming_hero\phone-store-server\node_modules\body-parser\lib\read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at invokeCallback (E:\programming_hero\phone-store-server\node_modules\raw-body\index.js:231:16)
at done (E:\programming_hero\phone-store-server\node_modules\raw-body\index.js:220:7)
at IncomingMessage.onEnd (E:\programming_hero\phone-store-server\node_modules\raw-body\index.js:280:7)
at IncomingMessage.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)"
app.put('/quantity/:id', async (req, res) => {
const id = req.params.id;
const quantity = req.body;
const updateQuantity = JSON.parse(quantity);
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
quantity: updateQuantity.quantity
}
};
const result = await phoneDB.updateOne(filter, updateDoc, options);
res.send(result);
})
react
and client site error is put URL is 404 and (bad Request)
const increase = () => {
setCount(count + 1)
const totalQuantity = count + number;
const url = `http://localhost:5000/quantity/${id}`
fetch(url, {
method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(totalQuantity)
})
.then(res => res.json())
.then(result => {
console.log(result);
})
}

Related

dataLoaded state only changed after page reloaded

I'm doing an API call to get some data. then I keep a useState called dataLoaded. on a successful API call I make the dataLoaded=true. but to see it changed I have to reload the page.
following is my code.
const [dataLoaded, setDataLoaded] = useState(false)
useEffect(() =>{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/movie/`+ path.eventId + `/venue/`+ path.venue +`/showtime`;
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
const fetchData = async () => {
try {
const response = await fetch(url, requestOptions());
const json = await response.json();
// console.log(json);
// console.log(json.data.venueDateShowtime)
setShowTimes(json.data.dateShowtimes[0].showtimes[0]);
console.log(json.data.dateShowtimes[0].date)
setShowdate(json.data.dateShowtimes[0].date);
setDataLoaded(true);
console.log(dataLoaded)
console.log(showTimes.showtimeId)
console.log(showdate)
if(dataLoaded){
getSeatsArrangement();
}
console.log('jjjj')
}
catch (error) {
console.log("error",error);
}
};
fetchData();
},[]);
const getSeatsArrangement = async () => {
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
console.log(showTimes.showtimeId)
console.log(showdate)
try{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/seat?venueId=` + path.venue + `&movieId=`+ path.eventId +`&showtimeId=1011&movieDate=2022-10-11`;
const response = await fetch(url,requestOptions());
const json = await response.json();
console.log(json)
setReservedSeats(json.data.reservedSeats.reservedSeat)
setNonReservedSeats(json.data.reservedSeats.nonReservedSeats)
console.log(reservedSeats)
console.log(nonReservedSeats)
} catch(error) {
console.log("error",error);
}
}
Console logs when page loads
What is the aim of the code? fetchData is performed once after page loading (because of using ,[] at the end of useeffect.
And a remark: If you log your state right after setting it, the previous value will be shown! you should define another useeffect with your state as dependency (for each state) and log your state in there.
useEffect(() => {
console.log(dataLoaded)
if(dataLoaded){
getSeatsArrangement();
}
console.log('jjjj')
}, [dataLoaded]);
useEffect(() => {
console.log(showTimes.showtimeId)
}, [showTimes]);
useEffect(() => {
console.log(showdate)
}, [showdate]);
useEffect(() =>{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/movie/`+ path.eventId + `/venue/`+ path.venue +`/showtime`;
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
const fetchData = async () => {
try {
const response = await fetch(url, requestOptions());
const json = await response.json();
// console.log(json);
// console.log(json.data.venueDateShowtime)
setShowTimes(json.data.dateShowtimes[0].showtimes[0]);
console.log(json.data.dateShowtimes[0].date)
setShowdate(json.data.dateShowtimes[0].date);
setDataLoaded(true);
}
catch (error) {
console.log("error",error);
}
};
fetchData();
},[]);

how to updata any data in database after sucessfully showing console?

As you can in the react (clint-side) code , i am trying increase/decrese of Quantity in database and UI.
in this code i am sucessfully show quantity in console . but i don't show it my UI and database . Now what should i do ?
Server side (react)
const { register, handleSubmit } = useForm();
const onSubmit = (data, event) => {
const url = https://nameless-dusk 43671.herokuapp.com/products/${productsId}
fetch(url, {
method: "PUT",
headers: {
'content-type': "application/json"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(result => {
console.log(result)
event.target.reset()
}
)
}
update item on clint side
app.put('/products/:id', async (req, res) => {
const id = req.params.id;
const updateUser = req.body;
const filter = { _id: ObjectId(id) }
const options = { upsert: true };
const updateDoc = {
$set: {
name: updateUser.name,
email: updateUser.email,
}
}
const result = await
ProductCollection.updateOne(filter, updateDoc,
options)
res.send(result)
})

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.How to fix

I am doing an online diary and get problems with fetching inside jsx component. I have 2 requests. First for fetching lessons and its returns dates and ids of lessons. And second that fetching marks in this lessons but second return [object Promise] but fetch is ok. So how I can get normal data(not a [object Promise]?
const [marks, setMarks] = useState([])
const [lessons, setLessons] = useState([])
const [loading, setLoading] = useState(true)
const getLessons = async(subjectID) => {
var res = await fetch("http://localhost:5002/graphql", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.authToken
},
body: JSON.stringify({
query: `query adad {
getSubjectLessons(subject:${subjectID}){
id,
date
}}`,
}),
}).then(data => data.json())
setLessons(res.data.getSubjectLessons)
getAllMarks(res.data.getSubjectLessons);
console.log(res.data.getSubjectLessons)
}
const getMark = async(pupilID, lessonID) => {
var res = await fetch("http://localhost:5002/graphql", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.authToken
},
body: JSON.stringify({
query: `query adad {
getPupilMarksByLesson(lesson: ${lessonID} , pupil:${pupilID}){
mark
}
}`,
}),
}).then(data => data.json())
if (res.data.getPupilMarksByLesson !== null) {
console.log(res.data.getPupilMarksByLesson.mark)
return res.data.getPupilMarksByLesson.mark
} else {
return res.data.getPupilMarksByLesson
}
}
const getAllMarks = (lessons) => {
return setMarks(lessons.map(el => {
return ( <th> {
getMark(p.pupilID, el.id)
} </th>)
}))
}
useEffect(() => {
getLessons(p.subjectID);
setLoading(false);
}, [])
You are using async/await and .then() improperly in some places. Try this way:
const [marks, setMarks] = useState([])
const [lessons, setLessons] = useState([])
const [loading, setLoading] = useState(true)
const getLessons = async(subjectID) => {
var res = await fetch("http://localhost:5002/graphql", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.authToken
},
body: JSON.stringify({
query: `query adad {
getSubjectLessons(subject:${subjectID}){
id,
date
}}`,
}),
})
var data = await res.json()
setLessons(data.getSubjectLessons)
getAllMarks(data.getSubjectLessons);
console.log(data.getSubjectLessons)
}
const getMark = async(pupilID, lessonID) => {
var res = await fetch("http://localhost:5002/graphql", {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.authToken
},
body: JSON.stringify({
query: `query adad {
getPupilMarksByLesson(lesson: ${lessonID} , pupil:${pupilID}){
mark
}
}`,
}),
})
var data = await res.json()
if (data.getPupilMarksByLesson !== null) {
console.log(data.getPupilMarksByLesson.mark)
return data.getPupilMarksByLesson.mark
} else {
return data.getPupilMarksByLesson
}
}
const getAllMarks = (lessons) => {
return setMarks(lessons.map(el => {
return ( <th> {
getMark(p.pupilID, el.id)
} </th>)
}))
}
useEffect(() => {
getLessons(p.subjectID);
setLoading(false);
}, [])
if you are using async and await then dont use .then syntax try to do like this
const getLessons = async (subjectID) => {
const res = await fetch('http://localhost:5002/graphql', {
method: 'post',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.authToken,
},
body: JSON.stringify({
query: ` query adad {
getSubjectLessons(subject:${subjectID}){
id,
date
}}`,
}),
});
const data = await res.json();
setLessons(data.getSubjectLessons);
getAllMarks(data.getSubjectLessons);
console.log(data.getSubjectLessons);
};
or simply you can use third party library like axios
install it with npm or yarn with following command npm i axios or yarn add axios
and try it like this
const getLessons = async (subjectID) => {
const data = {
query: `query adad {
getSubjectLessons(subject:${subjectID}){
id,
date
}}`,
};
const config = {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.authToken,
};
const { data } = await axios.post(
'http://localhost:5002/graphql',
data,
config
);
setLessons(data.getSubjectLessons);
getAllMarks(data.getSubjectLessons);
console.log(data.getSubjectLessons);
};
or make sure that you are not passing object in jsx.

Values won't update after api call with axios

I'm trying to fetch data with axios using React's useEffect in two steps:
1- Get the access token with a POST request
2- Use the token on another POST request to get the desired data
After the first post request, the response returns as expected, but the state value doesn't update. So it sends undefined as the token for the second request.
const [infos, setInfos] = useState(null)
const [token, setToken] = useState('')
useEffect(() => {
const getToken = async () => {
try {
const response = await axios.post(
'adress',
{
username: 'root',
password: 'i_want_my_token',
}
)
setToken(response.data.access)
} catch (error) {
console.log(error)
}
}
getToken()
const getCatalogo = async () => {
try {
let data = { id: 6 }
let configCatalogo = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
}
const catalogoResponse = await axios
.post(
'adress',
data,
configCatalogo
)
setInfos(res.data)
} catch (error) {
console.log(error) }
}
getCatalogo()
}, [])
Since the function to get/set your token is asynchronous, you need to use two different useEffects: one to fetch the token and one to use that token once it is set.
const [infos, setInfos] = useState(null)
const [token, setToken] = useState('')
useEffect(() => {
const getToken = async () => {
try {
const response = await axios.post(
'adress',
{
username: 'root',
password: 'i_want_my_token',
}
)
setToken(response.data.access)
} catch (error) {
console.log(error)
}
}
getToken()
}, []);
useEffect(() => {
const getCatalogo = async () => {
try {
let data = { id: 6 }
let configCatalogo = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
}
const catalogoResponse = await axios
.post(
'adress',
data,
configCatalogo
)
setInfos(res.data)
} catch (error) {
console.log(error) }
}
getCatalogo()
}, [token]);

How to create a Spotify playlist using react?

I am trying to create a playlist on localhost and then have the list I created to be saved to Spotify. Can someone help why Save to Spotify button might not be working? Everything else seems fine, I have doubts about the fetching part I used but can't figure out what the issue might be.
Screenshot of the page:
And there is the Spotify.js code:
import { SearchBar } from '../components/SearchBar/SearchBar';
const clientId = 'I've put my client id';
const redirectUri = 'http://localhost:3000/callback/';
let accessToken;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
let expiresIn = Number(expiresInMatch[1]);
//This clears the parameters, allowing to grab new access token then it expires
window.setTimeout(() => (accessToken = ''), expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then((response) => {
return response.json();
})
.then((jsonResponse) => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map((track) => ({
id: track.id,
name: track.name,
artists: track.artists[0].name,
album: track.album.name,
uri: track.uri,
}));
});
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userId;
return fetch(`https://api.spotify.com/v1/me`, { headers: headers })
.then((response) => response.json())
.then((jsonResponse) => (userId = jsonResponse.id))
.then((userId) => {
return fetch(`/v1/users/${userId}/playlists`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ name: name }),
})
.then((response) => response.json())
.then((jsonResponse) => {
const playlistId = jsonResponse.id;
return fetch(`/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: trackUris }),
});
});
});
},
};
export default Spotify;
Here is the screenshot of Element > Console:
I had an fetch error, updated as below and working now.
let accessToken;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
let expiresIn = Number(expiresInMatch[1]);
//This clears the parameters, allowing to grab new access token then it expires
window.setTimeout(() => (accessToken = ''), expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then((response) => {
return response.json();
})
.then((jsonResponse) => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map((track) => ({
id: track.id,
name: track.name,
artists: track.artists[0].name,
album: track.album.name,
uri: track.uri,
}));
});
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userID;
return fetch('https://api.spotify.com/v1/me', { headers: headers })
.then((response) => response.json())
.then((jsonResponse) => {
userID = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userID}/playlists`, {
method: 'POST',
headers: headers,
body: JSON.stringify({ name: name }),
})
.then((response) => response.json())
.then((jsonResponse) => {
const playlistID = jsonResponse.id;
return fetch(
`https://api.spotify.com/v1/users/${userID}/playlists/${playlistID}/tracks`,
{
method: 'POST',
headers: headers,
body: JSON.stringify({ uris: trackUris }),
}
);
});
});
}, // end of savePlaylist method
}; // end of Spotify object
export default Spotify;

Resources