Reputation: 137
I'm searching, as the topic name says, to populate a database with datas coming from an already exist graphql API.
My project is using Next.js, PostgreSQL, Apollo for GraphQL and Prisma to connect the whole. I managed to retrieve datas from the API and display these. Now I just want to store these datas in my Postgres database. So you know I'm using the Client-Side Rendering and not the other methods (SSR, SSG).
All documentations I found was about creating an API then post to the database which is not my case or documentation about create & createMany queries but with hardcoded datas. My research doesn't help me to see clear so I come here to find anyone who is willing to guide me. If have a clue I'll appreciate. Thank you =) !
To illustrate here a piece of code :
import { useQuery, gql } from "@apollo/client";
// query to retrieve 3 animes
const QUERY = gql`
query GetFirstsThree{
Page(page: 1, perPage: 3) {
media {
title {
userPreferred
}
}
}
}
`;
export default function AnimList() {
const { data, loading, error } = useQuery(QUERY);
if (loading) {
return <h2>Loading...</h2>;
}
if (error) {
return null;
}
const medias = data.Page.media;
return (
<div className="mainGrid">
{medias.map((value) => {
return (
<p>{value.title.userPreferred} </p>
)
})}
</div>
);
}
Upvotes: 1
Views: 322
Reputation: 137
Hello for those who have the same issue here is how i resolved my problem.
First I have created a async function to post my Anime.
async function savedAnime(anime){
const res = await fetch('api/anime', {
method: 'Post',
body: JSON.stringify(anime),
});
if(!res.ok){
throw new Error('Something went wrong');
}
return await res.json();
}
Then I added a submit input, which on its onClick event will map the medias the same way I did to display the anime's title, but here to store the datas in the database. After, I create a variable with my datas that I want to store. Finally, I call the function I've created before to post my Anime, on which I pass the variable.
And that pretty much all.
<input type="submit" value="Save Animes" onClick={ async () => {
try{
medias.map(async (value) => {
const anime = {
title: value.title.userPreferred,
coverImage: value.coverImage.medium,
};
console.log(anime);
savedAnime(anime);
})
} catch(err){
console.error(err);
}
}}/>
Upvotes: 0