DEV Community

Cover image for Fetching data depending on the date.
Caleb Alessandro Rodriguez
Caleb Alessandro Rodriguez

Posted on • Edited on

Fetching data depending on the date.

In the past three weeks of building my capstone project for a software engineering boot camp I'm close to graduating from, I came upon an issue(one of many). Every day I needed to fetch a prompt from my rails backend based on what date that prompt instance has. In this Dev-Blog, I'll show you what I came up with. I'm sure there's a better way, but this is mine.
Note: I'm using a JS react frontend and a ruby on rails backend

Let's start with the backend. First set up your resources.

rails g resource Prompt title date:date

make sure to use a date table when generating them. Once that's finished you can go ahead and migrate.

rails db:migrate

Okay cool, now let's look in the Prompt controller. You should have something like this.

class PromptsController < ApplicationController

end
Enter fullscreen mode Exit fullscreen mode

Before we forgot to go into the config file and down somewhere near the bottom should be a routes.rb file. Go ahead and add a new route to it, name it whatever you want, I'm going to name it...

get '/prompts/:date', to: 'prompts#show_prompt_by_date'
Enter fullscreen mode Exit fullscreen mode

Now, let's go ahead and make the method for grabbing the data by the date.

class PromptsController < ApplicationController

  def show_prompt_by_date 
     #grabbing the specific prompt using the params
     prompt = Prompt.find_by(date: params[:date])

     #rendering/error handling
     if prompt
        render json: prompt, status: :ok
     else
        render json: { errors: ["Prompt not found"] }, status: :not_found
     end
  end

  private

  #being safe
  def prompt_params
     params.permit(:date)
  end
end
Enter fullscreen mode Exit fullscreen mode

If you're using sterilizers go ahead and add date and whatever other table you want to show up in front of the attributes.

class PromptSerializer < ActiveModel::Serializer
  attributes :title, :date
end
Enter fullscreen mode Exit fullscreen mode

If you aren't then when you render the prompt render it with includes.

render json: prompt, include[:title, :date, status: :ok
Enter fullscreen mode Exit fullscreen mode

After all that lets add some seed data
seeds.rb

Prompt.destroy_all

Prompt.create!(title: "July, 15th, 2020", date: 7152022)
Prompt.create!(title: "March, 9th, 2020", date: 392022)
Prompt.create!(title: "March, 10th, 2020", date: 3102022)

puts "done seeding"
Enter fullscreen mode Exit fullscreen mode

Now go ahead and seed!
rails db:seed

That's it for the backend!

Now for the frontend.

First in whatever component you want to fetch the data in you'll need to set up a few things, I'll be using the hooks useState(for grabbing state) and useEffect(for fetching whenever window is loaded). Let's import that and also get and format the current date.

App.js

import React, { useState, useEffetc } from "react";

function App(){
  //setting up our useState for assigning a prompt 
  const [prompt, setPrompt] = useState([])

  //grabs the current date/time
  const currentDate = new Date();

  //formatting our date for fetching
  const date = `${current.getMonth()+1}${current.getDate()}${current.getFullYear()}`;

  return(
    <div>nothing here yet</div>
  )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now all that is left to do is set up our useEffect/fetch and do something with the fetched data.

App.js

useEffect(() => {
  //your url might be different, such as: http://localhost:4000/prompts/${date}

  fetch(`/prompts/${date}`)
  .then((r) => r.json())
  .then(data => {
     setPrompt(data)
     fetchPosts(data.id)
   })
}, [date]);

//doing something with the data
return (
  <div>{prompt.title} : {prompt.date}</div>
Enter fullscreen mode Exit fullscreen mode

That's pretty much it, run your backend with rails start and your front with npm start. Hopefully, this was helpful, thank you for reading.

Top comments (0)