I have a question about if i am correctly getting one value of the array supabase gives.
I use this code to do this
countries.value = parseInt(countries.value.map(({ aantal }) => aantal));
If i dont wrap it in a parsInt i get the number like: [2000]
So when i wrap it i get only 2000. Which is correct.
I also tested it with using .toString. Also works
My question:
Is doing it this way correct? Becuase i first was really confused why the number was wrapped in square brackets []
The complete code
<script setup>
import { ref, onMounted } from "vue";
import { supabase } from "./lib/supabaseClient";
const countries = ref();
async function getCountries() {
const { data } = await supabase.from("count").select("aantal");
countries.value = data;
console.log({ data });
countries.value = parseInt(countries.value.map(({ aantal }) => aantal));
}
async function updateplus() {
countries.value++;
console.log("update", countries.value);
const { data, error } = await supabase
.from("count")
.update({ aantal: countries.value })
.eq("id", 1)
.select();
console.log("update", { data, error });
}
onMounted(() => {
getCountries();
});
const nummber = countries.value;
</script>
<template>
<div>
{{ countries }}
{{ nummber }}
Count
</div>
<div><button #click="updateplus()">Plus 1</button></div>
</template>
If you are always expecting only one value then you should be using .single() along with that query. If however you are expecting zero to one row then you should use .maybeSingle(). If you don't use either of these methods then you will always get the data returned as an array.
const { data } = await supabase.from("count").select("aantal").maybeSingle();
I used this it look better
async function getCountries() {
const { data } = await supabase
.from("numbers")
.select("aantal")
.limit(1)
.single();
countries.value = data.aantal;
console.log({ data });
}
Related
I can't figure it out how to pass params to an anonymous function in Nuxt 3.
index.vue:
<template>
<form #submit.prevent="signUpNewsletter()">
<input type="email" placeholder="example#x.com" v-model="userEmail">
<input type="submit" value="Submit">
</form>
</template>
<script setup>
const userEmail = ref('x#x.de')
function signUpNewsletter () {
useAsyncData(
'newsletter',
() => $fetch('/api/sign_up_news', {
method: 'POST', // Post method works
body: {
email: userEmail.value
}
})
)
}
</script>
server/api/sign_up_news.js:
import { createClient } from '#supabase/supabase-js'
export default async (email) => { // can't read the parameter
const SUPABASE_KEY = 'key123'
const SUPABASE_URL = 'url.supabase.co'
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)
const { data, error } = await supabase
.from('newsletter')
.insert([{ email }]) // <<< Fails!
return data
};
working:
import { createClient } from '#supabase/supabase-js'
export default async () => {
const SUPABASE_KEY = 'key123'
const SUPABASE_URL = 'url.supabase.co'
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)
const { data, error } = await supabase
.from('newsletter')
.insert([{ email: 'hi#it.works' }]) // <<< Works!
return data
};
Do you know how to pass parameter into Nuxt 3 server/api? Or do you got a source? The official docs are blank at this moment.
Update, I just found out today that useBody is now deprecated and it is replaced with readBody.
See this issue for reference.
I don't think you're able to pass params directly into the functions the way you're doing.
In another part of the docs, it says that when you pass a body into the server/api function, you'll need to retrieve it using await useBody(event).
Use useBody
Its mention in the docs: https://v3.nuxtjs.org/guide/features/server-routes#handling-requests-with-body
you just need to read through
import { createClient } from '#supabase/supabase-js'
export default async (event) => { // can't read the parameter
const body = await useBody(event)
const SUPABASE_KEY = 'key123'
const SUPABASE_URL = 'url.supabase.co'
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)
const { data, error } = await supabase
.from('newsletter')
.insert([{ email: body.email }])
return data
};
I'm working with Next.js, I tried accessing data but got this error:
Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
My code:
import { getAllBusinessProfiles } from '../../lib/api';
const Profile = ({ allProfiles: { edges } }) => {
return (
<>
<Head>
<title>Profile</title>
</Head>
<Hero />
<section>
{edges.map(({ node }) => (
<div key={node.id}>
<Link href={`/profile/${node.slug}`}>
<a> {node.businessInfo.name} </a>
</Link>
</div>
))}
</section>
</>
);
}
export default Profile;
export async function getStaticProps() {
const allProfiles = await getAllBusinessProfiles();
return {
props: {
allProfiles
}
};
}
getAllBusinessProfiles from api.js:
const API_URL = process.env.WP_API_URL;
async function fetchAPI(query, { variables } = {}) {
const headers = { 'Content-Type': 'application/json' };
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({ query, variables })
});
const json = await res.json();
if (json.errors) {
console.log(json.errors);
console.log('error details', query, variables);
throw new Error('Failed to fetch API');
}
return json.data;
}
export async function getAllBusinessProfiles() {
const data = await fetchAPI(
`
query AllProfiles {
businessProfiles(where: {orderby: {field: DATE, order: ASC}}) {
edges {
node {
date
title
slug
link
uri
businessInfo {
name
title
company
image {
mediaItemUrl
altText
}
highlight
phone
city
country
facebook
instagram
email
website
profiles {
profile
profileInfo
}
extendedProfile {
title
info
}
}
}
}
}
}
`
);
return data?.businessProfiles;
};
What could be the error here? I used the getStaticProps method on Next.js but got the error above instead. Please, check. Thanks.
The error:
Server Error
Error: Error serializing .profileData returned from getStaticProps in "/profile/[slug]".
Reason: undefined cannot be serialized as JSON. Please use null or omit this value.
I don't know what could cause this though.
Add JSON.stringify when calling an asynchronous function that returns an object.
Try modifying your getStaticProps function like this.
export async function getStaticProps() {
const profiles = await getAllBusinessProfiles();
const allProfiles = JSON.stringify(profiles)
return {
props: {
allProfiles
}
};
}
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Source: MDN
I had this issue using Mongoose and Next.js.
To solve it: I switched from convert require to import then wrapped my result in JSON.parse(JSON.stringify(result));.
Good: import mongoose from 'mongoose';
Bad: const mongoose = require('mongoose');
I had the same serialization error when accessing a Vercel system environment variable in getStaticProps.
Using JSON.stringify did not do the trick, but String() worked. My code:
export async function getStaticProps() {
const deploymentURL = String(process.env.NEXT_PUBLIC_VERCEL_URL);
return {
props: {
deploymentURL,
},
};
}
Thanks to this GitHub issue for the inspiration
I had the same issue when I was working with redux with next js and the reason was one of the fields in the default state I set it to undefined. Instead I used null:
const INITIAL_STATE = {
products: [],
loading: false,
error: undefined,
cart: [],
};
error:undefined was causing the error. Because "undefined" cannot be serialized:
export async function getStaticProps() {
const allProfiles = await getAllBusinessProfiles();
return {
props: {
allProfiles
}
};
}
you are returning "allProfiles" which is the result of async getAllBusinessProfiles() which is either returning undefined, error or one of the fields of the returned object is undefined. "error" object is not serializable in javascript
Instead of using undefined, you have to use null as the value for your variables.
Note that the error shows you exactly which variable is using undefined as its value. Just modify its value to be null.
The value 'undefined' denotes that a variable has been declared, but hasn't been assigned any value. So, the value of the variable is 'undefined'. On the other hand, 'null' refers to a non-existent object, which basically means 'empty' or 'nothing'.
Source: [1]
I was having the same issue while trying to find a match in the array of data using the id. The issue I had was the items in the array had ids which were numbers while the value I was getting from params was a string. So all i did was convert the number id to a string to match the comparison.
export async function getStaticProps({ params }) {
const coffeeStore = coffeeStoreData.find(
(store) => store.id.toString() === params.slug[0]
);
return {
props: {
coffeeStore,
},
};
}
install a package called babel-plugin-superjson-next and superjson and added a .babelrc file with these contents:
{
"presets": ["next/babel"],
"plugins": ["superjson-next"]
}
see this topic : https://github.com/vercel/next.js/discussions/11498.
I had a similar problem too where I was fetching data through apollo directly inside of getStaticProps. All I had to do to fix the error was add the spread syntax to the return.
return {
props: {
data: { ...data }
}
}
return { props: { allProfiles: allProfiles || null } }
In getStaticProps() function, after fetching your data it will be in json format initially, but you should change it as follow:
const res = await fetch(`${APP_URL}/api/projects`);
const data = JSON.parse(res);
now it will work.
When you call api you should use try catch. It will resolve error.
Example:
import axios from "axios";
export const getStaticProps = async () => {
try {
const response = await axios.get("http:...");
const data = response.data;
return {
props: {
posts: data
}
}
} catch (error) {
console.log(error);
}
}
Hope help for you !
put res from API in Curly Brackets
const { res } = await axios.post("http://localhost:3000/api", {data})
return { props: { res } }
try this, it worked for me:
export async function getStaticProps() {
const APP_URL = process.env.PUBLIC_NEXT_WEB_APP_URL;
const res = await fetch(`${APP_URL}/api/projects`);
const projects = await res.json();
return {
props: {
projects: projects?.data,
},
};
}
I'm trying to fetch a data from my hosted database. The database itself are working (I have checked it from the swagger app) but no data is shown when it is called from API form.
import React from 'react';
export const getStaticPaths = async () => {
const res = await fetch('https://[server]/course');
const data = await res.json();
const paths = data.result.map(course => {
return {
params: { id: course._id.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('https://[server]/course/' + id);
const data = await res.json();
return {
props: { course: data }
}
}
const Details = ({ course }) => {
return (
<div>
<h1> { course.course_name } </h1>
<h1>a</h1>
</div>
);
}
export default Details;
The code is in the pages folder. I followed a tutorial on youtube from "netninja" and when I tried it on his code it works. I read somewhere that it won't work on components but I already put it on the pages but it still does not return anything.
Is there anything I can do ?
I got the answer. After checking console.log on the data. Looks like the data is on another array which is called result. so i needed to call the data from course.result.course_name. So the Answer is just to check console.log every once in a while. Shout out to juliomalves for pointing that out
Why split property is undefined here? I fetched the products from my product api through axios, I received json data that have some properties(name,description,...)
const [product, setProduct] = useState({});
let substrings=[];
useEffect(() => {
const getProduct = async () => {
try {
const res = await axios.get(`/products/${props.match.params.id}`);
setProduct(res.data);
} catch (error) {
console.error(error);
}
};
getProduct();
//eslint-disable-next-line
}, []);
const substrings = product.description.split(".");
This is the json that we get from products/id
{"_id":"1","name":"Mangoes","image":"https://drive.google.com/thumbnail?id=1Iq2F4fYxDi7HdX-IJcRuON-CbNuK-pxd","description":"This sweet and fresh mangoes make your day sweet","category":"Fruits","keywords":"fruits","price":120,"countInStock":0,"content":""}
whereas it works fine here
const [product, setProduct] = useState({});
const [desc,setDesc]=useState("");
useEffect(() => {
const getProduct = async () => {
try {
const res = await axios.get(`/products/${props.match.params.id}`);
setProduct(res.data);
setDesc(res.data.description);
} catch (error) {
console.error(error);
}
};
getProduct();
//eslint-disable-next-line
}, []);
const substrings = desc.split(".");
Can anyone tell us why is it so?
I think before the load product, the value of your product is null or {},
so when you use product.description the value will be undefined.
You can use:
const substrings = (product?.description || '').split(".");
I think the problem here is the way you declared the product using useState. For the second part you declare the description directly so when you split it, it might be an empty string or whatever you declared it, but not undefined.
But for the first part, you declare just the product variable, without the description property. So before fetching, when you try to split product.description, it is undefined and becomes a value just after fetching.
In order to fix it you might declared the product like this:
const [product, setProduct] = useState({ description: "" }) or just simply use ? operator like this: const substrings = product.description?.split(".");
Also there might be a problem because you first declare substrings as an empty array and then you declare it again as a const.
How can i send a request to graphql using relay onclick ?
render(){
<div>
<img src={this.state.picture}>
<input type="email" value={this.state.email} onChange{...}/>
<button onClick={this.checkEmail}>Check</button>
</div>
}
checkEmail = async () => {
const res = await axios({
method: 'post',
url: __RELAY_API_ENDPOINT__,
data: {
query: `query CheckEmail($email: String!){lookupEmail(email: $email){id, picture}}`,
variables: {"email": this.state.email}
}
});
//set state using res
}
I cant figure out how to do this with relay.
In the examples relay is used to fetch and render onMount.
But how would i get data and change state on event listeners (onclick) ?
I couldnt find any example like that .
you can declare data dependency in relay but in some cases when you had a paginationcontainer which will fetch not 'all' e.g. first: 10 so we cannot get the length of it, in this case, you need to declare another data dependency by doing request. I hope you understand what I'm trying to say.
This is how i do it in my code, u need to explore the relay props more:
getPublicTodosLengthForPagination = async () => { // get publicTodos length since we cannot get it declared on createPaginationContainer
const getPublicTodosLengthQueryText = `
query TodoListHomeQuery {# filename+Query
viewer {
publicTodos {
edges {
cursor
node {
id
}
}
pageInfo { # for pagination
hasPreviousPage
startCursor
hasNextPage
endCursor
}
}
}
}`
const getPublicTodosLengthQuery = { text: getPublicTodosLengthQueryText }
const result = await this.props.relay.environment._network.fetch(getPublicTodosLengthQuery, {}) // 2nd arguments is for variables in ur fragment, in this case: e.g. getPublicTodosLengthQueryText but we dont need it
return await result.data.viewer.publicTodos.edges.length;
}
componentDidMount = async () => {
let result = await this.getPublicTodosLengthForPagination();
this.setState((prevState, props) => {
return {
getPublicTodosLength: result
}
});
}
implement this on ur code then update me.best of luck!