Persisting Data to your website

gobias101
2 min readMar 3, 2022

This blog will talk about some of the ways to persist data to your JavaScript/React website. We talked about API’s in a previous blog, it turns out that the way to persist data to your own app is to create your own API that will communicate with your app to upload and download the data you want to your site!

To get started, you create a new rails app, but when generating the app flag it as an API so the generator only creates the relevant files for an API. Type this into your command prompt in the folder you want to create your API in:

$ rails new plane_view_api --api

You can read more about generating API’s on the rails guide website here:

Once you have your API generated, set it up by generating resources for the models and controllers you will need for your app and fill them out. My Trips controller for my new Plane View app looks like this, I have created actions for both creating and displaying users trips:

class tripsController < ApplicationController
def index
trips = trip.all
render json: trips
end

def create
@trip = trip.new(trip_params)

if @trip.save
render json: @trip, status: :created, location: @trip
else
render json: @trip.errors, status: :unprocessable_entity
end
end

private

def trip_params
params.require(:trip).permit(:user, :route, :date, :local_time, :side, :pictures, :comments)
end
end

Now, users can submit new data to my app and also view data others have submitted. There are a few ways to have your front end communicate with the back end API, you can either use simple GET/POST requests like this on your front-end:

Get Data:getAllTrips() {
return fetch(URL-to-backend)
.then(res => res.json())
.then(data => {
for(let i = 0; i < data.length; i ++) {
new Trip(data[i].id, data[i].name...);
}
})
};
Send Data:fetch(URL-to-backend, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
trip: {
name: tripName
}}),
})
.then(res => {
return res.json()
})
.then(data => {
(Code to manipulate data here)
})

This will get you started on communicating between your front-end and back-end. When creating more complex websites such as the ones you will build in React, it is better to use the middle-ware Redux to control communication actions. We will delve more into using Redux for communicating between your front and back end in another blog!

--

--