how to fetch data from database
Hey, I'm new to wasp and react. I have been trying to fetch data from the database (just like the already built in admin dashboard but from a different model in the DB). I have already created a model in the database. but was unable to get it to fetch data. its not the coding part that I have the issue in, its on what files I should make changes to get the job done. Hope what I told make sense. It would be great if you can help me out with the walkthrough of getting this job done!
4 Replies
Hi @Maochi. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To fetch data from the database in a Wasp application, you need to follow these steps:
1. Define a query in your
main.wasp
file.
2. Implement the query function in your server-side code.
3. Use the query in your React component.
Let's go through each step:
1. Define a query in main.wasp
:
Add a query declaration to your main.wasp
file, like this:
Replace getYourData
with an appropriate name for your query, and YourEntity
with the name of the entity you want to fetch.
2. Implement the query function:
Create or update a file named queries.js
(or queries.ts
if you're using TypeScript) in your src
directory. Implement your query function there:
Replace YourEntity
with the name of your entity. You can customize the query as needed, for example, by adding filters or sorting.
3. Use the query in your React component:
In your React component file (e.g., MainPage.jsx
or MainPage.tsx
), import and use the query:
This approach is based on the information from Wasp Docs: Querying the Database and Wasp Docs: Working with Queries.
Remember to replace YourEntity
and getYourData
with appropriate names for your specific use case. Also, make sure your entity is properly defined in your main.wasp
file.
If you need more detailed information about working with entities and queries in Wasp, you can refer to these resources:
- Wasp Docs: Working with Entities
- Wasp Docs: Implementing Queries in Node
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
Sorry @Maochi, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:
Perhaps try again in 15mins?did that work @Maochi ?
I'd advise going though Wasp's tutorial to get familar with the basics of Wasp: https://wasp-lang.dev/docs/tutorial/create
1. Creating a New Project | Wasp
You'll need to have the latest version of Wasp installed locally to follow this tutorial. If you haven't installed it yet, check out the QuickStart guide!
Yeah hi, thats mb i didnt see that section in the documentation.. ill let you know how it goes