Perform Data Fetching and Mutations in SolidStart with createAsync

Daniel Afonso
InstructorDaniel Afonso
Share this video with your friends

Social Share Links

Send Tweet

Most applications involve some level of data fetching and data mutations.

To fetch data in a SolidStart application, we can leverage createAsync, a primitive that turns a promise into a signal.

In this lesson, we will learn how to leverage createAsync to fetch data from our previously defined API Route. We will also leverage our API Route to perform some data mutations.

[00:00] Now that we have our API routes, it is time to get rid of the hardcoded data and start fetching it. The way to do data fetching in SOLID Start is by using the create a sync primitive. In our index file, let us start by deleting this create signal and importing create a sync from SolidRouter. Then let's create a user's const and [00:19] call create a sync. Create a sync expects a promise, so let's pass it a fetch call that will do a GET request to our API slash users API route and return it to JSON. Now, if we check our app, it still works, and we are getting our data via the API request. The next scenario to handle is our dynamic route where we [00:39] want to get the user data depending on which route is visited. Let's also start by deleting this create signal and importing create a sync from SolidRouter. Then let's create a user const and call create a sync with a get request to our route. Here you can see we are missing something. We need to provide this endpoint with the ID of the user we [00:59] want to fetch the data for. Luckily, dynamic routes receive the dynamic part of its URL into its props parameters. And as we call this dynamic route ID, we should expect that value to be in an ID property. So let's get our props, type them, and use them in our fetch call to get the ID of the user we want to [01:19] fetch. Now if we check our app running, we should be fetching data for each specific user. Besides data fetching, we also have a mutation scenario in our form. Let's implement it. In our route, let's add a non submit handler and prevent default. Then let's get our form data and set up a post request with [01:39] fetch. In this request, we need to pass our form data inside the body and that should be all we need for our post request. Now whenever we add data, we don't want to stay on our form, so let's leverage solid router use navigate to have a navigation call and send us back to our index route after our post request. Finally, [01:59] if we check our page, we should see that both the mutation and the data fetching is working.