I m trying to get an array from react frontend (stored in local storage) to my view class in django but i'm getting this error:
In console:
GET http://127.0.0.1:8000/api/quiz/multiple/ 500 (Internal Server Error)
Django LOGS:
for quiz in quizzes:
TypeError: 'NoneType' object is not iterable
ERROR:django.server:"GET /api/quiz/multiple/ HTTP/1.1" 500 20064
Here's how i store the data in the LocalStorage:
localStorage.setItem('quizzes', JSON.stringify(quizList));
history.push('/start')
And here's how i get it from local storage and pass it to the django using axios:
export default function QuizPage() {
const [DataState,setDataState] = useState([]);
const storedQuizzes = JSON.parse(localStorage.getItem("quizzes"))
useEffect(() => {
axiosInstance
.get(`quiz/multiple/`, {
quizzes: storedQuizzes
}).then((res) => {
setDataState(res.data);
})
.catch((function (error) {
console.log(error)
}));
}, [setDataState]);
and, finally, that's my django view:
class MultipleQuizView(APIView):
permission_classes = [IsAuthenticated]
def get(self,request):
questionsList = []
quizzes = request.data.get('quizzes')
for quiz in quizzes:
currentQuiz = Quiz.objects.get(url=quiz)
quizSerializer = QuizSerializerForMultipleQuizzes(currentQuiz)
question = Question.objects.filter(quiz__url=quiz)
questionSerializer = QuestionSerializer(question, many=True)
quizSerializerData = quizSerializer.data.copy()
quizSerializerData["questions"]=questionSerializer.data
questionsList.append(quizSerializerData)
if questionsList:
return Response(questionsList)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
I'm pretty sure the problem isn't from my view class because i tested it using Postman and it works without any problem.
EDIT:
I just tryed with postman using this body and it works properly:
https://i.stack.imgur.com/3RJ5A.png
So i need to send data from react like this but i don't know how:
{
"quizzes":["securitate","aparare"]
}
Try changing the second param to axios.get as follows:
axiosInstance
.get(`quiz/multiple/`, {
params: {
quizzes: storedQuizzes
}
}).then(...)
Read more about the properties that the second param supports.
SOLVED!
The problem was that i wrote:
quizzes = request.data('quizzes')
instead of:
quizzes = request.data['quizzes']
Related
Hello I am new to react native and particullary firebase. I've been watching tutorial about using firebase with react native and i read the react native firebase documentation but i am stuck. I have data in my firestore data base, in my collection called user but I am not able to read, to get the data from it. Here is my firestore database :
and here is how I tried to get the data in my component :
const Profile = ({navigation, ...props}) => {
async function getUserData () {
const userCollection = await await firebase.firestore().collection('users').doc(firebase.auth().currentUser.uid).get()
return userCollection
}
console.log('🐲' + getUserData())
this return me that : [object Object]
I also tried this, (it was how it was done in the instagram clone tutorial of Adrian Twarog) :
const Profile = ({navigation, ...props}) => {
function getUserDataFirstTry() {
firebase.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.get()
.then((snapchot) => {
if(snapchot.exists){
console.log('🦜' + snapchot.data())
} else {
console.log('merde ca marche pas')
}
})
}
console.log('🐲🐲' + getUserDataFirstTry())
But I get the same result in my console : [object Object]
I tried to put my function in a useEffect hook but this changes nothing.
Can you tell me what I am doing wrong ? (if possible in the second example because it's realtime changes). Thanks.
As Nicholas commented, since you're concatenating snapchot.data() to a string, you get the string representation of that object, which is pretty useless.
To log a specific field from the data:
console.log('🦜' + snapchot.data().userName)
To log all fields from the data in a more useful format:
console.log('🦜' + JSON.stringify(snapchot.data()))
Note: the proper spelling is snapshot (not snapchot), but I kept your original spelling here for ease of copy/paste.
I'm working with Nuxt in SSR mode and want to build out a dynamic sitemap for multiple routes/ data sets.
The issue I'm facing now is that the async/ await function only allows 'data' as the variable. The same function with 'post' as the variable leads to a "map function does not exist"
This is what's in my Nuxt.config.js file
sitemap: {
hostname: "https://example.com",
routes: async () => {
let { data } = await axios.get('https://api.example.com/api/v1/locations');
data = data.data.map((loc) => `/locations/${loc.slug}`);
console.log(data);
let { posts } = await axios.get('https://cms.example.com/wp-json/wp/v2/posts');
posts = posts.map((post) => `/posts/${post.slug}`);
console.log(posts);
data.concat(posts);
return data
},
path: '/sitemap.xml'
}
The resulting output I'm looking for should be formatted like this:
[
'/locations/location-one',
'/locations/location-two',
'/locations/location-three',
'/posts/post-one',
'/posts/post-two',
'/posts/post-three',
]
The error I'm getting:
Cannot read property 'map' of undefined
and it's occuring on this line:
posts = posts.map((post) => `/posts/${post.slug}`)
so it appears to me that it's not accepting 'posts' as a valid variable for its own await function.
That call works fine when the first call is commented out and 'data' is used instead of 'posts'
your destructured response is wrong:
replace:
let { posts } = ...
by:
let { data: posts } = ...
Because Axios always returns a "data" attribute, so you just have to rename it as "posts".
Your array concatenation must be like that:
data.concat(posts);
(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)
The push() method is only to push one item, but not an array of item.
(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
Im creating my first CRUD in Vue/Laravel and now I'm trying to send a create to my backend application, this is my code:
Frontend:
async addDespesa() {
let uri = "api/despesas/create";
const response = await axios.get(uri, this.despesa).then((response) => {
this.$router.push({ name: "despesas" });
});
},
Backend:
public function create()
{
//
}
Errors in inspect on Browser:
>[vue-router] Route with name 'despesas' does not exist
>Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/".
at createRouterError
at createNavigationDuplicatedError
at HashHistory.confirmTransition
at HashHistory.transitionTo
at eval
at HashHistory.push
at new Promise
at VueRouter.push
at eval
Your backend seems fine, the problem is in the .then part of your Axios call:
this.$router.push({ name: "despesas" });
You should check your frontend routes (probably in a file called routes.js) and make sure you have a route named despesas. So something like this:
let routes = [
{
'path': '/path/to/despesas',
'name': 'despesas',
component: require('./path/to/despesas-component').default
},
...
other routes
];
I have below graphl api query that i am using to send the data from react front app with the object to get the desired results
{
allSectionRequests(data:{
requestStageName:"Request Submitted"
}){
section
type
}
}
and then i am trying to pass variable from react like below
export const GET_SECTIONREQUESTS = gql`
query AllSectionRequests($data: sectionRequestParamsInput){
allSectionRequests(data: $data){
section
type
}
}
`;
I have attached the image that i need to send to graphql api below
and the below is the react code that i will be calling query inside component and then passing data object to graphql api
const { data: dashBoardData, loading: dashBoardDataLoading, error: dashBoardDataError } = useQuery(GET_SECTIONREQUESTS, {
variables: { data: { requestStageName: 'Request Submitted' } },
});
I am getting error like this below
The variable **data** type is not compatible with the type of the argument **data**.
↵Expected type: SectionRequestParamsInput.
i am not sure where i am doing wrong with this code, could any one please help on this one .
Many thanks
I have rectified my problem with the below solution
export const GET_SECTIONREQUESTS = gql`
query AllSectionRequests($sectionRequestParamsInput: SectionRequestParamsInput){
allSectionRequests(data: $sectionRequestParamsInput){
id
section
type
createdBy
description
status
age
}
}
`;
and then changed my input parameters in react like this
const { data: dashBoardData, loading: dashBoardDataLoading, error: dashBoardDataError } = useQuery(GET_SECTIONREQUESTS, {
variables: { sectionRequestParamsInput: { requestStageName: 'Request Submitted' } },
});
i hope this will helps to any person who is looking for graphql api query with parameters passed in.
I am trying to use the Fetch API with my Rails application. I can pass parameters to the controller as part of a query string, but still can't figure out how to pass JSON data or where to find it in the controller. A sample call looks like the below. Where can I access my test data on in the controller? Happy Sunday :)
export const fetchControllerData = () => {
return fetch('api/users',), {
body: { "test": "test" }
})
.then(res => res.json());
};
I'm in the process of working out my own issues with fetch and Rails. But I'll take a stab at this.
I expect that fetch is using GET as the default method - which won't use the body at all. You will likely need to set the method to be POST to get the body through. Further to that you might need to set the Content-Type header (to application/json) in order to send the data through as JSON.
May be u need to send params in this way for get request and use this link for https://github.com/axios/axios
export const fetchControllerData = () => {
params = { body: { "test": "test" } }
return HTTP.get('api/users', params)
.then((response) => {
if (response.success) {
// do something here
} else {
// handle error condtion here
}
});
}