React time based function - javascript

I am trying to create an api post function that sends when the timeout reaches 45 seconds and when the user clicks the cancel button the post request stops or you clear the timeout to stop it.
I did something that works but after another 45 secs it makes another post requirement. is there way to make the post request after the 45 seconds and then cancel the request when user clicks the cancel button
import { makeStyles } from "#material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'
const useStyles = makeStyles(styles);
function processorder({ query: { name, number, location, ordermessage, price, } }) {
const classes = useStyles();
const [processed, setProcessed] = useState(false)
const [canceled, setCanceled] = useState(false)
const [time, setTime] = useState()
const [data, setData] = useState({})
const Id = setTimeout(() => {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Api-key': 'ml7h7L8nN8Q2yA',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
},
body: JSON.stringify({
client: name,
client_phone: number,
restaurant: "Chitis",
location: location,
ordermessage: "Jollof Rice",
amount: "500"
})
};
fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setData(result.data)
setProcessed(true);
return () => clearTimeout(Id)
})
.catch(error => console.log('error', error));
}, 45000);
const cancel = () => {
clearTimeout(Id);
setCanceled(true);
if (canceled == true) {
alert("canceled")
}
};
return (
<div>
<h3> processing Order<h3>
(processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding to payment</h3>)
(canceled == false ? (<Button onClicK={cancel} />) : <h3>order canceled</h3>
</div>
)
}
processorder.getInitialProps = ({ query }) => {
return { query }
};
export default processorder

You could wrap your whole timeout function in an if, which is dependant on state. However, this isn't very robust as changing the data or the time also sends a duplicate request:
import { makeStyles } from "#material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'
const useStyles = makeStyles(styles);
function processorder({ query: { name, number, location, ordermessage, price, } }) {
const classes = useStyles();
const [processed, setProcessed] = useState(false)
const [canceled, setCanceled] = useState(false)
const [time, setTime] = useState()
const [data, setData] = useState({})
if (!canceled && !processed) {
const Id = setTimeout(() => {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Api-key': 'ml7h7L8nN8Q2yA',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
},
body: JSON.stringify({
client: name,
client_phone: number,
restaurant: "Chitis",
location: location,
ordermessage: "Jollof Rice",
amount: "500"
})
};
fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setData(result.data)
setProcessed(true);
return () => clearTimeout(Id)
})
.catch(error => console.log('error', error));
}, 45000);
}
const cancel = () => {
clearTimeout(Id);
setCanceled(true);
if (canceled == true) {
alert("canceled")
}
};
return (
<div>
<h3> processing Order<h3>
(processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding to payment</h3>)
(canceled == false ? (<Button onClicK={cancel} />) : <h3>order canceled</h3>
</div>
)
}
processorder.getInitialProps = ({ query }) => {
return { query }
};
export default processorder
It would probably be better for you to do the whole fetch & timeout inside a clickHandler, with the timeout checking that canceled is false before sending the request.

import { makeStyles } from "#material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'
const useStyles = makeStyles(styles);
function processorder({ query: { name, number, location, ordermessage, price, } }) {
const classes = useStyles();
const [processed, setProcessed] = useState(false)
const [canceled, setCanceled] = useState(false)
const [time, setTime] = useState()
const [data, setData] = useState({})
const [id, setId] = useState()
const cancel = () => {
clearTimeout(id);
setCanceled(true);
if (canceled == true) {
alert("canceled")
}
};
useEffect(() => {
const Id = setTimeout(() => {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Api-key': 'ml7h7L8nN8Q2yA',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
},
body: JSON.stringify({
client: name,
client_phone: number,
restaurant: "Chitis",
location: location,
ordermessage: "Jollof Rice",
amount: "500"
})
};
fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setData(result.data)
setProcessed(true);
clearTimeout(Id);
})
.catch(error => console.log('error', error));
}, 45000);
setId(Id);
console.log(data)
}, []);
return (
<div>
<h3> processing Order<h3>
(processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding to payment</h3>)
(canceled == false ? (<Button onClicK={cancel} />) : <h3>order canceled</h3>
</div>
)
}
processorder.getInitialProps = ({ query }) => {
return { query }
};
export default processorder

Related

How to pass State in Context React and use this an another components

I am trying this code with useContext. i want to take this response.data.message in Editdata.js component. how did i do? how i will send this state message using context.
auth-context.js
const AuthContext = React.createContext({
updatePlayer: () => {},
});
export const AuthContextProvider = (props) => {
const [msg, setmsg] = useState();
const playerupdate = async (updatedPlayer) => {
const { id, player_fname, player_lname, player_nickname } = updatedPlayer;
await axios
.post(
"https://scorepad.ominfowave.com/api/adminPlayerUpdate",
JSON.stringify({ id, player_fname, player_lname, player_nickname }),
{
headers: { "Content-Type": "application/json" },
}
)
.then((response) => {
fetchPlayerList()
//navigate('/view-players');
setmsg(response.data.message)
})
.catch((error) => {
alert(error);
});
};
return (
<AuthContext.Provider
value={{
updatePlayer: playerupdate
}}
>
{props.children}
</AuthContext.Provider>
);
};
type here
Editdata.js
function Editdata() {
const authcon = useContext(AuthContext);
const submitupdateForm = (e) => {
e.preventDefault();
const playerdetail = {
player_fname: firstname,
player_lname: lastname,
player_nickname: nickname,
id: empid
}
authcon.updatePlayer(playerdetail)
}
return (
<form onSubmit={submitupdateForm}>
</form>
);
}
How is the correct way to pass state between components with useContext?

Component rendering before finishing the useEffect

I have a component (ownPrescriptionsPanel) inside which I'm rendering another component (PrescriptionsList). Inside the parent component, I have a useEffect hook to fetch data using Axios for the child component (PrescriptionsList). The problem is no matter what I try, the PrescriptionsList is always empty and only gets populated when I refresh. I have three child components (all are PrescriptionsList components) but I've shown only one in the below code.
import React, { useEffect, useState } from "react";
import Axios from "axios";
import { PrescriptionsList } from "../../components/prescriptionsList/prescriptionsList";
import "./ownPrescriptionsPanelStyles.css";
export const OwnPrescriptionsPanel = () => {
const [pastPrescriptions, setPastPrescriptions] = useState([]);
const [openPrescriptions, setOpenPrescriptions] = useState([]);
const [readyPrescriptions, setReadyPrescriptions] = useState([]);
const [isBusy1, setIsBusy1] = useState(true);
useEffect(() => {
Axios.post(
"http://localhost:3001/getpatientprescriptions",
{
id: sessionStorage.getItem("id"),
},
{
headers: {
"Content-Type": "application/json",
},
}
).then((response) => {
console.log("getpatientprescriptions", response.data);
var resArr = []; //getting rid of the duplicates
response.data.filter(function (item) {
var i = resArr.findIndex(
(x) => x.prescriptionId === item.prescriptionId
);
if (i <= -1) {
resArr.push(item);
}
return null;
});
setPastPrescriptions(resArr);
setIsBusy1(false);
});
}, []);
if (isBusy1) {
return <div>loading</div>;
}
return (
<>
<PrescriptionsList
pastPrescriptions={pastPrescriptions}
heading="All prescriptions"
viewOnly={true}
prescriptionStatusOpen={false}
showPharmacy={false}
/>
</>
);
};
Edit: Given below is the code for PrescriptionList component
import React, { useState } from "react";
import Axios from "axios";
import DescriptionTwoToneIcon from "#mui/icons-material/DescriptionTwoTone";
import PresciptionModal from "../prescriptionModal/prescriptionModal";
import "./prescriptionsListStyles.css";
export const PrescriptionsList = ({
pastPrescriptions,
heading,
viewOnly,
showPharmacy,
}) => {
const [prescriptionDetails, setprescriptionDetails] = useState([]);
const [prescriptionDrugList, setPrescriptionDrugList] = useState([]);
const [open, setOpen] = useState(false);
const handleClose = () => {
console.log("close");
setOpen(false);
};
console.log("pastPrescriptions", pastPrescriptions);
const getPrescriptionDrugDetails = async (prescriptionId) => {
await Axios.post(
"http://localhost:3001/prescriptionDrugDetails",
{
prescriptionId: prescriptionId,
},
{
headers: {
"Content-Type": "application/json",
},
}
).then((response) => {
console.log("prescriptionDrugDetails", response.data);
setPrescriptionDrugList(response.data);
});
};
const handlePrescriptionClick = async (prescriptionDetails) => {
console.log("prescriptionDetails", prescriptionDetails);
setprescriptionDetails(prescriptionDetails);
await getPrescriptionDrugDetails(prescriptionDetails.prescriptionId);
setOpen(true);
};
const pastPrescriptionsList = pastPrescriptions.map((d) => (
<div
value={d}
onClick={() => handlePrescriptionClick(d)}
key={d.drugId}
className="prescriptionListItem"
>
<div style={{ width: "30px" }}>
<DescriptionTwoToneIcon fontSize="small" />
</div>
{d.prescriptionId}
</div>
));
const markPrescriptionComplete = async (d) => {
await Axios.post(
"http://localhost:3001/markcomplete",
{
prescriptionId: d.prescriptionDetails.prescriptionId,
pharmacyId: d.prescriptionDetails.pharmacyId,
},
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(
"prescriptionId, pharmacyId",
d.prescriptionDetails.prescriptionId,
d.prescriptionDetails.pharmacyId
);
window.location.reload(true);
};
return (
<div className="prescriptionsListContainer">
<div className="viewPrescriptionsLabel">{heading}</div>
<div className="prescriptionsContainer">{pastPrescriptionsList}</div>
{open && (
<PresciptionModal
open={open}
onClose={handleClose}
prescriptionDetails={prescriptionDetails}
prescriptionDrugList={prescriptionDrugList}
viewOnly={viewOnly}
// prescriptionStatusOpen={false}
markprescriptioncomplete={markPrescriptionComplete}
showPharmacy={showPharmacy}
/>
)}
</div>
);
};
I tried solution 1, solution 2 and the code shown above is using solution from geeksforgeeks. None seem to be working

How can i fix this error? ERROR TypeError: null is not an object (evaluating 'userdata.user')

How can i fix this error in my project? the error is ERROR TypeError: null is not an object (evaluating 'userdata.user') i am using react native expo after logging into my app and entering mainpage its giving me this error can anyone can help me to fix this error? i today send 8 hours fixing this error but i can't able to fix it can anyone can help me with that?
import { StyleSheet, Text, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import { containerFull } from '../../CommonCss/pagecss'
import { formHead } from '../../CommonCss/formcss'
import Bottomnavbar from '../../Components/Bottomnavbar'
import TopNavbar from '../../Components/TopNavbar'
import FollowersRandomPost from '../../Components/FollowersRandomPost'
import AsyncStorage from '#react-native-async-storage/async-storage';
import * as Location from 'expo-location';
const Mainpage = ({ navigation }) => {
const [userdata, setUserdata] = React.useState(null)
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [city, setCity] = useState(null);
const [data, setData] = useState(null)
useEffect(() => {
AsyncStorage.getItem('user')
.then(data => {
// console.log('async userdata ', data)
setUserdata(JSON.parse(data))
})
.catch(err => alert(err))
}, [])
console.log('userdata ', userdata)
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
let city = await Location.reverseGeocodeAsync(location.coords);
setCity(city[0].city);
})();
}, []);
const sendCity = () => {
setCity(city);
fetch('http://192.168.1.52:3000/updateCity', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
city: city,
username: userdata.user.username
}),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
useEffect(() => {
sendCity();
}, [])
return (
<View style={styles.container}>
<StatusBar />
<TopNavbar navigation={navigation} page={"MainPage"} />
<Bottomnavbar navigation={navigation} page={"MainPage"} />
<FollowersRandomPost />
</View>
)
}
export default Mainpage
const styles = StyleSheet.create({
container: {
width: '100%',
height: '100%',
backgroundColor: 'black',
paddingVertical: 50,
}
})
And why something city value becomes null and something new york which is correct how to fix null?
import { StyleSheet, Text, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import { containerFull } from '../../CommonCss/pagecss'
import { formHead } from '../../CommonCss/formcss'
import Bottomnavbar from '../../Components/Bottomnavbar'
import TopNavbar from '../../Components/TopNavbar'
import FollowersRandomPost from '../../Components/FollowersRandomPost'
import AsyncStorage from '#react-native-async-storage/async-storage';
import * as Location from 'expo-location';
const Mainpage = ({ navigation }) => {
const [userdata, setUserdata] = useState(null);
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [city, setCity] = useState(null);
const [data, setData] = useState(null);
useEffect(() => {
async function getUserData() {
try {
const userDataString = await AsyncStorage.getItem('user');
const userData = JSON.parse(userDataString);
setUserdata(userData);
} catch (err) {
alert(err);
}
}
getUserData();
}, []);
useEffect(() => {
async function getLocation() {
try {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
let city = await Location.reverseGeocodeAsync(location.coords);
setCity(city[0].city);
} catch (err) {
console.error(err);
}
}
getLocation();
}, []);
useEffect(() => {
async function sendCity() {
try {
setCity(city);
const response = await fetch('http://192.168.1.52:3000/updateCity', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
city: city,
username: userdata.user.username
}),
});
const data = await response.json();
console.log('Success:', data);
} catch (err) {
console.error('Error:', err);
}
}
if (userdata) {
sendCity();
}
}, [userdata]);
console.log(city)
return (
<View style={styles.container}>
<StatusBar />
<TopNavbar navigation={navigation} page={"MainPage"} />
<Bottomnavbar navigation={navigation} page={"MainPage"} />
</View>
);
}
export default Mainpage
You need to wait AsyncStorage to finish his task before using the new data, how about using top lvl await like :
useEffect(() => {
await AsyncStorage.getItem('user')
.then(data => {
// console.log('async userdata ', data)
setUserdata(JSON.parse(data))
})
.catch(err => alert(err))
}, [])
console.log('userdata ', userdata)
for the 2nd question if you set city state inside the useEffect and with userdata dependency this will trigger the function when userdata state change, and since city initial state is null, and you can't immediatly get the new state from getLocation neither in sendCity, without rerender your component, i think you need to add one more condition before running the function, but this might have some side effect from the useEffect..
useEffect(() => {
async function sendCity() {
try {
const response = await fetch('http://192.168.1.52:3000/updateCity', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
city: city,
username: userdata.user.username
}),
});
const data = await response.json();
console.log('Success:', data);
} catch (err) {
console.error('Error:', err);
}
}
if (userdata && city) {
sendCity();
}
}, [userdata, city]);

TypeError: cardsData.map is not a function

I am supposed to store queries for users in the cardsData and I need to map through the data in cardsData but if I run the code on my terminal i get this error. I am a newbie and I have searched a lot of forums that suggest that cardsData is supposed to be an array but I do not know how to go forward from there. I am just following a youTube tutorial and that was exactly what was done in the tutorial.
it worked on the youTube why can’t it work for me too?
please somebody help.
[enter image description here][1]import { useContext } from 'react'
import { TinderContext } from '../context/TinderContext'
import { SiTinder } from 'react-icons/si'
import CardHeader from './CardHeader'
import CardFooter from './CardFooter'
import TinderCardItem from './TinderCardItem'
const style = {
wrapper: `h-[45rem] w-[27rem] flex flex-col rounded-lg overflow-hidden`,
cardMain: `w-full flex-1 relative flex flex-col justify-center items-center bg-gray-500`,
noMoreWrapper: `flex flex-col justify-center items-center absolute`,
tinderLogo: `text-5xl text-red-500 mb-4`,
noMoreText: `text-xl text-white`,
swipesContainer: `w-full h-full overflow-hidden`,
}
const Card = () => {
const { cardsData } = useContext(TinderContext)
return (
<div className={style.wrapper}>
<CardHeader />
<div className={style.cardMain}>
<div className={style.noMoreWrapper}>
<SiTinder className={style.tinderLogo} />
<div className={style.noMoreText}>
No More Profiles in your Location...
</div>
</div>
<div className={style.swipesContainer}>
{cardsData.map((card, index) => (
<TinderCardItem card={card} key={index} />
))}
</div>
</div>
<CardFooter />
</div>
)
}
export default Card
I just edited this post and below is my TinderContext
import { useState, createContext, useEffect } from 'react'
import faker from '#faker-js/faker'
import { useMoralis } from 'react-moralis'
export const TinderContext = createContext()
export const TinderProvider = ({ children }) => {
const { authenticate, isAuthenticated, user, Moralis } = useMoralis()
const [cardsData, setCardsData] = useState([])
const [currentAccount, setCurrentAccount] = useState()
const [currentUser, setCurrentUser] = useState()
useEffect(() => {
checkWalletConnection()
if (isAuthenticated) {
requestUsersData(user.get('ethAddress'))
requestCurrentUserData(user.get('ethAddress'))
}
}, [isAuthenticated])
const checkWalletConnection = async () => {
if (isAuthenticated) {
const address = user.get('ethAddress')
setCurrentAccount(address)
requestToCreateUserProfile(address, faker.name.findName())
} else {
setCurrentAccount('')
}
}
const connectWallet = async () => {
if (!isAuthenticated) {
try {
await authenticate({
signingMessage: 'Log in using Moralis',
})
} catch (error) {
console.error(error)
}
}
}
const disconnectWallet = async () => {
await Moralis.User.logOut()
setCurrentAccount('')
}
const handleRightSwipe = async (cardData, currentUserAddress) => {
const likeData = {
likedUser: cardData.walletAddress,
currentUser: currentUserAddress,
}
try {
await fetch('/api/saveLike', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(likeData),
})
const response = await fetch('/api/checkMatches', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(likeData),
}
)
const responseData = await response.json()
const matchStatus = responseData.data.isMatch
if (matchStatus) {
console.log('match')
const mintData = {
walletAddresses: [cardData.walletAddress, currentUserAddress],
names: [cardData.name, currentUser.name],
}
await fetch('/api/mintMatchNft', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(mintData),
})
}
} catch (error) {
console.error(error)
}
}
const requestToCreateUserProfile = async (walletAddress, name) => {
try {
await fetch(`/api/createUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userWalletAddress: walletAddress,
name: name,
}),
})
} catch (error) {
console.error(error)
}
}
const requestCurrentUserData = async walletAddress => {
try {
const response = await fetch(
`/api/fetchCurrentUserData?activeAccount=${walletAddress}`,
)
const data = await response.json()
setCurrentUser(data.data)
} catch (error) {
console.error(error)
}
}
const requestUsersData = async activeAccount => {
try {
const response = await fetch(
`/api/fetchUsers?activeAccount=${activeAccount}`,
)
const data = await response.json()
setCardsData(data.data)
} catch (error) {
console.error(error)
}
}
return(
<TinderContext.Provider
value={{ connectWallet,
disconnectWallet,
cardsData,
currentAccount,
currentUser,
handleRightSwipe
}}
>{children}
</TinderContext.Provider>
)
}
It's very likely your state cardsData is not being initialized correctly as an [] or its been set wrongly to a value different than an Array.
Hard to go further than this without TinderContext code

400 BAD REQUEST when POST using Axios in React

Can any help me with this?
I keep getting a 400 bad request from Axios.
I can pass a GET request and confirm its working fine.
I create http-common.js file with following code:
import axios from 'axios';
export default axios.create({
baseURL: 'https://5fa97367c9b4e90016e6a7ec.mockapi.io/api',
headers: {
'Content-type': 'application/json'
}
});
Then,I create a service that uses axios object above to send HTTP requests.
TodoService.js
import http from '../http-common/http-common';
const getAll=()=>{
return http.get('/todos');
};
const get=id=>{
return http.get(`/todos/${id}`);
};
const create=data=> {
return http.post('/todos',data);
};
const update=(id,data)=>{
return http.put(`/todos/${id}`,data);
};
const remove = id => {
return http.delete(`/todos/${id}`);
};
const removeAll = () => {
return http.delete(`/todos`);
};
const findByTitle = title => {
return http.get(`/todos?title=${title}`);
};
export default {getAll,get,create,update,remove,removeAll,findByTitle};
Then, I use TodoDataService.create(data) ... in AddTodos component.
AddTodos.js
import React, { useState } from 'react';
import TodoDataService from '../services/TodoService';
const AddTodos = () => {
const initialTodoState={
id:null,
title: '',
isDone: false,
user: ''
};
const [todo,setTodo]=useState(initialTodoState);
const [submitted,setSubmitted]=useState(false);
const handleInputChange=event=>{
const {name,value}=event.target;
setTodo({...todo,[name]:value});
};
const saveTodo =()=>{
var data={
title: todo.title,
isDone:todo.isDone,
user: todo.user
};
console.log(data);
TodoDataService.create(data)
.then(response => {
setTodo({
id:response.data.id,
title: response.data.title,
isDone: response.data.isDone,
user: response.data.user
});
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
const newTodo=()=>{
setTodo(initialTodoState);
setSubmitted(false);
};
return (
<div className="submit-form">
{submitted ? (
<div> //...
) : (
<div>
<div className="form-group"> //... </div>
<div className="form-group"> //... </div>
<button onClick={saveTodo} className="btn btn-success">
Submit
</button>
</div>
)}
</div>
)
}
export default AddTodos;
When clicked Submit it's giving this error:
I recreate your api call and got this response:
await fetch('https://5fa97367c9b4e90016e6a7ec.mockapi.io/api/todos', {
method: 'POST', body: JSON.stringify({id: "123",title: "homework", isDone: false, user: "foo"})})
.then(response => response.json())
.then(data => {
console.log(data)
})
error 400 "Max number of elements reached for this resource!"
you need to delete some records in order to insert new ones
so after deleting a record:
await fetch('https://5fa97367c9b4e90016e6a7ec.mockapi.io/api/todos/1', {
method: 'DELETE'})
.then(response => response.json())
.then(data => {
console.log(data)
})
VM623:5 {id: "1", title: "deneme", isDone: true, user: "cafererensimsek"}
and posting a new one, now it works

Categories

Resources