Not able to push my data in an json server - javascript

This is a local JSON server you can see on this URL
http://localhost:3003/CourseList/1
My hooks
const [subjectName,setsubjectName]=useState(
{
id: "",
subjectname: "Aptitude",
chapter: [
{
chapter1: "",
topic: [
{
topic1: ""
}
]
}
]
}
);
function when I click on add button which will check if it matches the id of a prop then it will perform the task
const addSubject = async id => {
console.log("id "+id);
axios.get(`http://localhost:3003/CourseList/`)
.then((res)=>{
res.data.map((list,index)=>{
if(list.id===props.id){
console.log(list.subject)
list.subject.push(subjectName);
}
})
})
.catch((error)=>{
console.log(error);
})
};
How can I push new data in the subject array? I am getting nothing

Here's the solution
const addSubject = async id => {
console.log("id "+id);
try{
const {data} = await axios.get("http://localhost:3003/CourseList")
data.map(async(item)=>{
if(item.id===id){
console.log(item);
item.subject.push(subjectName);
await axios.put(`http://localhost:3003/CourseList/${id}`,item)
}
})
const check= await axios.get(http://localhost:3003/CourseList/${id})
console.log(check)
}catch(err){
console.log(err.message)
}
};

If you're using a JSON-server it should have a default endpoint for PATH/PUT your new object. You need to send the Content/Type: application/json in your request header and set the jsonServer.bodyParser in your server.

Related

Is it possible to post multiple data i.e., array of object using POSTMAN

Like
[
{
"enear": "",
"inten": 1,
"sctor": "Eny",
"topic": "",
"insight": ""
},
{
"enear": "",
"inten": 1,
"sctor": "Eny",
"topic": "",
"insight": ""
}
]
If possible how to write the nodejs code
This is my code
router.post("/post" , async (req,res) => {
const data = new Model(req.map(r => ({
enear: r.body.enear,
inten:r.body.inten,
sctor: r.body.sctor,
topic: r.body.topic,
insight: r.body.insight,
})))
try{
const dataToSave = await data.save()
res.status(200).json(dataToSave)
}catch(error){
res.status(400).json({message:error.message})
}
})
Does map works here?
I have tried using map . Is there any possible way please suggest
You can send an array in the body part and access an array using
req.body and use req.body.map here if it satisifies the condition
Array.isArray(req.body)
router.post("/post" , async (req,res) => {
const { body } = req;
if (Array.isArray(body)) {
const data = new Model(body.map(r => ({
enear: r.body.enear,
inten:r.body.inten,
sctor: r.body.sctor,
topic: r.body.topic,
insight: r.body.insight,
})))
try{
const dataToSave = await data.save()
res.status(200).json(dataToSave)
}catch(error){
res.status(400).json({message:error.message})
}
}
You can specify the array in Body -> Raw (select JSON format):
Then, you should be able to access your data with:
router.post('/post', async (req, res) => {
const { array } = req.body;
try {
const savedData = [];
for (const obj of array) {
const data = await Model.create({
enear: obj.enear,
inten: obj.inten,
sctor: obj.sctor,
topic: obj.topic,
insight: obj.insight,
});
savedData.push(data);
}
res.status(200).json(savedData);
} catch (error) {
res.status(400).json({ message: error.message });
}
});

React Native AsyncStorage read the data after user input

I have a question, so i'm using AsyncStorage to store the user input data as a json format. However , while i'm checking whether the data are stored correctly using console.log, it always print out undefined, so i'm curious about how to access the data i store and print it out so that i can check if the data is correct? thanks!
Here's the json formate that i want the user input to store in
////JSON FORMAT////
const MyRecipeData = [
{
name: recipeName,
video_cover: selectedVideoCover,
video_url: UploadVideo,
servings: servingSize,
channel_name: channelName,
publish_date: uploadDate,
ingredients: ingredientsInput,
directions: directionsInput,
},
];
////JSON FORMAT////
and these are the function that called after the user pressing upload button, and i try to read it using getAllinput function, but not sure i did it right or not
////------- Save all DATA --------------------////
const SaveAllInput = async () => {
await AsyncStorage.setItem("MyRecipeData", JSON.stringify(MyRecipeData))
.then(() => {
alert("your Recipe " + MyRecipeData.name + " has been saved");
})
.catch(() => {
console.log("error");
});
getAllInput();
};
////------- Save all DATA --------------------////
////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////
const getAllInput = async () => {
try {
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
NewRecipeData !== null ? JSON.parse(NewRecipeData) : null;
console.log(NewRecipeData);
return NewRecipeData;
} catch {
console.log(error);
}
};
////------- READING THE DATA THAT UPLOAD PREVIOUSLY-------- /////
the console.log(NewRecipeData) print out [{}] in my terminal, seems like i did not read my data properly
i tried to use getItem to read it out, but instead i got undefined or [{}]
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
NewRecipeData !== null ? JSON.parse(NewRecipeData) : null;
You using const and you are redefining the variable, try to console.log like this :
const NewRecipeData = await AsyncStorage.getItem("MyRecipeData");
console.log(NewRecipeData);
You are caliing getAllInput(); without await
const SaveAllInput = async () => {
const MyRecipeData = [
{
name: recipeName,
video_cover: selectedVideoCover,
video_url: UploadVideo,
servings: servingSize,
channel_name: channelName,
publish_date: uploadDate,
ingredients: ingredientsInput,
directions: directionsInput,
},
];
await AsyncStorage.setItem('MyRecipeData', JSON.stringify(MyRecipeData))
.then(() => {
alert('your Recipe ' + MyRecipeData.name + ' has been saved');
})
.catch(() => {
console.log('error');
});
await getAllInput();
};

Why doesn't it return the user from the database by id?

I use ORM Sequelize(Postgres). I wrote a code that should return user data by user id, but either it just doesn't return anything, or it says "Support for {where: 'raw query'} has been removed.".
async findOne(req,res) {
try {
const {id} = req.body;
console.log(id);
const user = await User.findOne({where: id})
return res.json({user});
} catch (e) {
console.log(e.message);
}
}
router.post('/getOne', userController.findOne);
You should use an object notation in order to indicate the condition id=:id:
const user = await User.findOne({where: { id: id } })
// OR
const user = await User.findOne({where: { id } })

re-render the component when retrieving data

When i fetch data from firebase the request still running and the data is still running in the console i don't know why it didn't stop
i used cleanup function, abort controller but it didn't work
here is my code
i hope you can help me
const [fetchedPhoto, setFetchedPhoto]= useState({
imagUrl:[]
})
const retrieveImg= useCallback(async() => {
try{
const url=[]
const data= await fetch('https://naif-65aa6.firebaseio.com/test-project.json',{signal:controller.signal})
const response= await data.json()
for(const key in response){
url.push({
id: key,
name: response[key].name,
phone: response[key].phone
})
}
setFetchedPhoto(prevState=>({
...prevState,
imagUrl: prevState.imagUrl.concat(url)
}))
console.log(fetchedPhoto.imagUrl);
} catch(err) {
console.log(err);
}
},[fetchedPhoto])
useEffect(()=>{
retrieveImg()
return()=>controller.abort()
},[fetchedPhoto])

How to store ID of record in Firebase cloud functions

I'm saving data in the collection in the following way:
const userEntry= {
UserId: "I want documentID here",
UserName: "",
creationDate: ""
}
const churchResult = await saveChurchData(userEntry)
const saveData = async (data: object) => {
return database.collection('users').add(data)
.then(snapshot => {
return snapshot.get().then(doc => {
doc.data()
return doc.id
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}
Is there any way that I store "documentID" of users table in the place of UserId. How can we do that in firebase cloud functions? I'm unable to find a way to store the documentID in the documentation.
I tried following, but it is giving wrong ID not docuemntID:
const key =firebase.database().ref().push()
Since I don't see any saveChurchData() method in your code, I make the assumption that instead of doing
const churchResult = await saveChurchData(userEntry)
you wan to do
const churchResult = await saveData(userEntry)
The following would do the trick, by using the doc() method without specifying any documentPath:
const userEntry = {
UserName: "",
creationDate: ""
}
const churchResult = await saveData(userEntry)
const saveData = async (data: object) => {
try {
const docRef = database.collection('users').doc();
const docId = docRef.id;
await docRef.set({ UserId: docId, ...data });
return docId;
} catch (error) {
//...
}
}

Categories

Resources