So now that we got push notifications working,
let's see how we can work with them from inside the app
so that when we press this trigger notification button,
we send a push notification.
For that, Expo has got us covered as well.
Here, in triggerNotificationHandler,
or wherever you wanna send a push notification,
in the place where you wanna trigger
that a push notification should be delivered to some device,
you need to send a http request to Expo's servers.
So we can do this with the fetch API,
which is available in React-Native,
and the URL to which you need to send this
is https://exp.host/--/API/v2/push/send.
Make sure you have no typo in there.
That is the URL to Expo's push notification server,
which we will leverage to deliver our push notification
to a different device.
This, in the end, was used behind the scenes,
when we used this testing tool here.
So we need to send a request there,
and we need to configure this request
with the second argument
we can provide to the fetch method here,
to the fetch function.
There we need to set the http request method to POST
because we need to send a post request to that URL,
and we need to add some special headers.
The headers we need to add here are the Accept header,
where we should accept application/json,
the Accept-Encoding header,
where we accept gzip, deflate,
and the Content-Type header,
where we also specify application/json.
In addition to those headers, we now need to set the body,
which will hold the actual message we wanna send.
Message is now, not just a string,
but an object, because after all,
there were a lot of things we could configure.
So, here on body, we simply provide an object,
however, not like this,
instead it needs to be in json format,
so we stringify this object with JSON.stringify
and then in there we can set up various things.
Most importantly, we need the to property.
This is a required property, which then needs our token,
the token we're getting when we're registering.
Now currently, we only have the token here,
we can simply use useState
to manage the token as state of our component.
There we got the pushToken and the setPushToken function.
We wanna set the push token once we got the token, here,
setPushToken to token and then go down
to the triggerNotificationHandler function
and there we wanna send to our pushToken here.
Now we can configure all the other fields
we can set on notifications.
We can for example, add the data field
and set this to extraData some data.
But of course, most of all, we can also set a title
which will be displayed
and there that could be send via the app,
whoops sent via the app,
and a body for the push notification which could be
this push notification was sent via the app.
Now this will send a http request to Expo's back-end servers
which then, in turn, will do all the rest
for delivering this push notification
to the device with this pushToken.
So, let's save this, and let's give it a try.