Hello everyone,
I am currently trying to upload a simple survey through the front end. I am working with nextjs. The schema is pretty simple, having just a tittle and an array of questions. But everytime I am trying to upload the survey to the database I am getting a document with an empty array… Like so :
so the front end looks like this
import React, { useState, useEffect } from "react"
import axios from "axios"
function NewSurvey() {
const [questions, setQuestions] = useState([])
const [text, setText] = useState("")
const [title, setTitle] = useState("0")
const addQuestion = () => {
setQuestions([
...questions,
{
id: questions.length,
name: text,
},
])
setText("")
console.log(questions)
console.log(title)
}
const submitSurvey = async () => {
console.log("surveyData is:", title, questions)
try {
const { data } = await axios.post(
"/api/postSurvey",
{ title: title, questions: questions },
{
headers: {
"content-type": "application/json",
},
}
)
console.log("submitting...", data)
} catch (error) {
console.log("error:", error)
}
}
return (
<div>
<input value={title} onChange={(e) => setTitle(e.target.value)}></input>
<>title</>
<input value={text} onChange={(e) => setText(e.target.value)}></input>
<button onClick={addQuestion}>Add question</button>
<ul>
{questions.map((question) => (
<li key={question.id}>
{question.id + 1}.{question.name}
</li>
))}
</ul>
<button onClick={() => submitSurvey()}>Submit survey</button>
</div>
)
}
So this is it for the front end part, as you can see, I’ve logged out the data before the axios request and it returns as expected.
Now here is my api/postSurvey
file
//api
import connectDB from "../../lib/connectDB"
import Surveys from "../../lib/models/surveySchema"
const { log } = console
export default async function postSurvey(req, res) {
const {reqSurveyData} = req?.body
log("requested Data:", reqSurveyData)
await connectDB()
try {
await Surveys.create({ reqSurveyData })
res.status(201).json({ message: "Data inserted successfully!" })
} catch (error) {
res.status(400).json({ error })
console.error(error)
}
}
here I’ve logged the body and it is returning a title
and array of questions
I think that my mistake lies in my api file but I cannot put my hand on what exactly.
here are the return of my consoles:
requested Data: {"title":"not working :(","questions":[{"id":0,"name":"why ?"},{"id":1,"name":"isn't working?"},{"id":2,"name":"thanks "}]}
Has anyone encountered similar issues ? any help is of course greatly appreciated