I want to display a list of meals from my rails backend to my react frontend. In addition, I'd like to add a specific date.
Here is what I have so far:
meals_controller.rb
def index
@meals = Meal.where(week_day: Date.today.cwday).order('random()')
@date = DateTime.now
render json: @meals.to_json(include: :restaurant)
end
MealsPage.js:
componentDidMount() {
axios.get('/meals.json')
.then(response => {
this.setState({
meals: response.data
});
})
.catch(error => console.log(error))
}
I'd like to add @datein the render method so that I could do something like:
this.setState({
meals: response.data.meals,
date: response.data.date
});
But everything I have tried so far has failed. I've tried things like:
render json: [@meals.to_json(include: :restaurant), @date]
or
render json: {meals: @meals.to_json(include: :restaurant), date: @date}
But both of these solutions send my @meals as one big string like "[{}, {}, {}]" instead of rendering it as an array of objects.
Any idea on I can make this work ?
mealsto render. The data are fetched from the backend correctly but it is on the react that the error is raised:reponse.data.mealsdoes not seem to work.